Reading from file using fgets

岁酱吖の 提交于 2019-12-28 04:19:05

问题


I am reading from file of format

1 32 43 23
32 43
123 43 54 243 
123 2222
2

Here is my code snippet.

string[100];
while(!feof(fp))
    fgets(string,100,fp)

Now, when I put every string, in the last string I am getting repetition and some more ambiguities (like something else also gets printed say 123 or so).

How to solve this problem?


回答1:


You need to check the return value of fgets. If a read has been successful, fgets returns the pointer to the buffer that you passed to it (i.e. string in your example). If the End-of-File is encountered and no characters have been read, fgets returns NULL.

Try this:

char string[100];
while(fgets(string, 100, fp)) {
    printf("%s\n", string);
}



回答2:


The eof is only reached after you have attempted to read from a file that is at the end. You have to use the return value of fgets instead (which returns NULL on eof or error and the pointer it is given otherwise):

char string[100];
while(fgets(string, 100, fp))
    // do stuff with string

Checking the return value like this will cause you never to hit the eof inside the body of the loop, like the other one, instead of in the condition.



来源:https://stackoverflow.com/questions/9434207/reading-from-file-using-fgets

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!