Sunday, August 2, 2009

C question about fgets?

Hi all. I'm writing a very simple C program to read a file and print it out again. Here's my code:





main()


{


FILE *file;


char line[80];





/** OPEN FILE **/


file = fopen("count.txt","r");





/** READ FILE **/


while(!feof(file)){


fgets(line,80,file);


printf("%s",line);





}








/** CLOSE FILE **/


fclose(file);





}





My count.txt has just 'abc' and then I pressed enter without typing anything in the next line and save. The problem when I do that is that it will print out abc again. So it will print out :





abc


abc





I'm totally confused why it's repeating the line again. It's the same if I change my 'count.txt'. Whenever I press enter without entering anything it will always repeat the last line.





Anyone know what I'm missing here? Thanks a lot for your help!

C question about fgets?
ff1100k points out the issue correctly. feof doesn't check if the next attempt at reading from file will hit the end of file. It only checks if your file stream has a end-of-file flag set on it, presumably from a previously failed I/O operation.





If you reach the end of the file, it's because none of the previous reads from the file failed. (Because if they failed, you would never have reached the end of the file). But then, if not a single I/O operation failed, how is the end-of-file flag going to be set on the stream? Because that is what feof checks for.





Since fgets returns null on an error or end of file, you can use that directly in the while condition...





while(fgets(...)) { ... }





I'm curious, where did you get the idea that using feof would work?
Reply:simple?! idk what your talkin about at all
Reply:In addition to checking the state of feof(), you have to check the return value of fgets(). What happens is this:





call feof() - returns false


call fgets() - reads "abc", file reading stops at "\n".


call printf() "abc"


call feof() - returns false (file system has not hit the end yet)


call fgets() - fails returns NULL. previous value of line is not changed.


call printf() - prints "abc" - the previous value of line.


call feof() - returns true.








To Tiffenii: This is the programming and design forum. It's common for people to ask programming questions here.
Reply:Return Value


On success, the function returns the same str parameter.


If the End-of-File is encountered and no characters have been read, the contents of str remain unchanged and a null pointer is returned.


If an error occurs, a null pointer is returned.


Use either ferror or feof to check whether an error happened or the End-of-File was reached.


No comments:

Post a Comment