Search code examples
cinputuser-input

Why do I get a segmentation fault when getting file name using user input?


I will strip the code down to only the parts I am having trouble with.

When I do the following, the code works

int main() {        
    FILE * fptr1 = fopen("in.txt", "r");
    fread(data, sizeof(char), size, fptr1);
    .
    .
    .
    FILE * fptr2 = fopen("out.txt", "w");
    fwrite(data, sizeof(char), size, fptr2);
    fclose(fptr2);
}

But when I use fgets to get the input and output file name using fgets or scanf, I get a segmentation fault.

int main() {

    char inputfile[100];
    char outputfile[100];
    printf("name of input file: \n");
    fgets(inputfile, 100, stdin);
    printf("name of output file: \n");
    fgets(outputfile, 100, stdin);
    .
    .
    .
}

I have been playing around with this for a while. I tried using scanf and tried changing the allocated sizes for inputfile and outputfile but I keep getting:

Segmentation fault (core dumped)

Solution

  • With fgets(), the resulting filenames inputfile and outputfile contain the terminating newline characters. It causes the following fopen() failed and returned NULL.

    However, you didn't check for nullity of FILE*'s before calling fread() or fwrite(), and this led to segmentation fault.