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.
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 iffp
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: