Search code examples
csegmentation-faultfile-handling

Getting segmentation fault while from a file using fscanf in c


int main() {
    FILE *matrix_r;
    matrix_r=fopen("matrix.txt","r");
    double x;char c;
    while(feof(matrix_r)){
        fscanf(matrix_r,"%lf%c",&x,&c);
        printf("%lf%c",x,c);
    }
    fclose(matrix_r);

    return 0;
}

Trying to read float values from the file but getting segmentation fault core dumped error. matrix.txt stores a matrix of floats.

contents of matrix.txt are below.

0.000000,876.671546,448.879717,1349.827396
876.671546,0.000000,1319.195209,964.193445
448.879717,1319.195209,0.000000,1741.628261
1349.827396,964.193445,1741.628261,0.000000

Solution

  • fopen() failed and feof(NULL) caused the segfault. If fopen() was successful then feof() would return false and the loop wouldn't run but your program wouldn't segfault.

    Check the return value of fopen() & fscanf(). You only need to call feof() if you need to find out why fscanf() failed to read 2 items.

    #include <stdio.h>
    
    int main() {
        FILE *matrix_r = fopen("matrix.txt", "r");
        if(!matrix_r) {
            perror("fopen");
            return 1;
        }
        for(;;) {
            double x;
            char c;
            int rv = fscanf(matrix_r, "%lf%c", &x, &c);
            if(rv != 2)
                break;
            printf("%lf%c", x, c);
        }
        fclose(matrix_r);
    }
    

    Here is the output:

    0.000000,876.671546,448.879717,1349.827396
    876.671546,0.000000,1319.195209,964.193445
    448.879717,1319.195209,0.000000,1741.628261
    1349.827396,964.193445,1741.628261,0.000000