0
votes

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
You will have to check if fopen fails.Sajith Eshan
Check the return value of fopen(). Also, the size of x[i] is 5, you should have fgets(x[i], 5, fp), or better yet, fgets(x[i], sizeof(x[i]), fp).Filipe Gonçalves
works fine for me with an existing and readable "wageData.txt"; try using a debugger or at some printf()s to get more intormationIngo Leonhardt
You also have to check if fgets fails if (NULL==fgets(...)) {...}Weather Vane
oops my bad sorry forks..should have checked the man page firstmSatyam

1 Answers

2
votes

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;
}