Segmentation fault while trying to test fgets()

126 views Asked by At

I'm trying to write a program to experiment with the fgets() function, with which I have little experience. I keep getting a segmentation fault 11 error when I run the program (but no errors when I compile it) and I don't know enough about fgets to know what is going on. Here is my program:

#include <stdio.h>

int main (void) {
    FILE *fp;
    fp = fopen("wageData.txt","r+");
    char x[3][5];
    int i = 0;
    while (i < 3) {
        fgets(x[i], 4, fp);
        i++;
    }

    for (i = 0; i < 3; i++) {
        printf("%s\n", x[i]);
    }

    return 0;
}

Here is the text file that I have linked to it:

Hi, my name is Frank.  
I like pie.  
My car is black.
1

There are 1 answers

0
Clifford On BEST ANSWER

I have built and executed your code with your suggested data, and it executes without error. However, you do not check that the call to fopen() is successful, and if fp is not a valid open file pointer, it does indeed abort.

I suspect in that case that the file was not opened; perhaps it was not in the current working path, was incorrectly named (POSIX file-systems for example are case sensitive), or was other wise locked (perhaps open elsewhere).

Equally it would be wise to check the success of fgets() so that it will work with files shorter then three lines:

#include <stdio.h>

int main(void) 
{
    FILE *fp = fopen("wageData.txt", "r+");
    if( fp != 0 )
    {
        char x[3][5];
        int i = 0;
        int j ;
        char* check = 0 ;
        while( i < 3 && fgets(x[i], 4, fp) != 0 ) 
        {
            i++;
        }

        for( j = 0; j < i; j++) 
        {
            printf("%s\n", x[j]);
        }
    }
    else
    {
        printf( "File not opened.\n" ) ;
    }

    return 0;
}