csegmentation-faultfile-conversion

Writing to a file in C segmentation Fault


I have a function that gets a string from the user and then does the following


void TraverseFile(char *inFile, char *outFile)
{
    FILE *pIn;
    FILE *pOut;
    pIn = fopen(inFile, "r");
    char c;
    if (pIn == NULL)
    {
        printf("File not found");
    }
    pOut = fopen(outFile, "w");
    if (pOut == NULL)
    {
        fclose(pIn);
        printf("The write file cannot be opened.\n");
        exit(1);
    }
    else{
        while(1) //while it is not the end of input file
        {
            c= putchar(tolower(fgetc(pIn)));
            if (feof(pIn)) break;
            fputc(c,pOut);
        }
        fclose(pOut);
    }
    fclose(pIn);
}

Two things are happening: the while loop is giving me a segmentation fault. I think after input is because fgetc() returns in an int and I want to convert to a char. And the creation of the second file has a weird dot next to the txt name (see picture).

creation error


Solution

  • At least these problems

    Missing .h

    Add

    #include <ctype.h>
    #include <stdio.h>
    #include <stdlib.h>
    

    Wrong type

    fgetc() returns an int to handle the typical 257 different return values. @Avi Berger

    // char c;
    int c;
    

    Using a char value that is negative and not EOF is undefined behavior with tolower(). By saving in int, c will have a value in the unsigned char range or EOF.

    while(!feof(pIn)) wrong

    Why is “while( !feof(file) )” always wrong?

    int c;
    while((c = fgetc(pIn)) != EOF) {
      c = tolower(c);
      fputc(c,pOut);
    }
    

    Error lacks exit

    When pIn == NULL, no point in continuing. @Retired Ninja

    if (pIn == NULL) {
      printf("File not found");
      exit(1); // Add
    }
    

    Without an early exit, fclose(pIn); is undefined behavior as pIn==NULL.

    Bad file name

    OP has "creation of the second file has a weird dot next to the txt name". Certainly due to improper filename formation like insufficient buffer size for the name.