I have a function to read from a file:
void input(char* buffer, FILE* fp)
{
char temp[100];
fgets(temp,100,fp);
strcpy(buffer,temp);
buffer [strlen(buffer)-1]=0;
}
And I file:
1
2
3
4
5
The last line terminates with a newline.
I try to read the file this way:
FILE* fp=fopen("myfile.txt","r");
while(!feof(fp))
{
char buffer[100];
input(buffer,fp);
puts(buffer);
}
It reads succesfully all the five strings: “1”,”2″,”3″,”4″,”5″ and prints them, but after the 5th string is printed, I get segmentation fault.
This is a common anti-pattern in C (and other languages, really) to set up a loop like yours that checks
!feof(fp). The problem is that this function returns true only after a read has failed due to EOF. The issue is that you use the results of your read before you check if the read even succeeded.I suggest you check the return value of
fgets(), it will returnNULLif there is an EOF. Propagate that value back and return it from yourinput()function. Then use that in your loop condition.Just to add, the seg fault itself is likely in your call to
strcpy(). Whenfgets()fails, you attempt to copy a buffer of uninitialized data, which could contain literally anything andstrcpy()may find a “string” much longer than your buffer. Even if it happens to find something shorter, your result will still be garbage.