1
votes

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)
2
Check inputfile and outputfile. Do they contain the terminating '\n'?timrau
Ok, but will the \n cause a segmentation fault? As far as I know, segmentation fault is caused by accessing memory outside of the allocated memory. Shouldn't the \n simply cause the program not to be able to find the file because the name is wrong?user6005857

2 Answers

4
votes

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.

1
votes

A string inputted using fgets() contains a terminating '\n', which is usually unexpected. Although this won't cause a segfault directly, it may cause fopen() to return NULL, since it cannot find that file. Trying reading data from a null file pointer will cause a segfault.

Add

if(fptr1 == 0)
{
    perror("fopen()");
    exit(EXIT_FAILURE);
}

after your fopen() statements.