Reading text-file until EOF using fgets in C
在C中使用fgets进行EOF之前,读取文本文件的正确方法是什么? 现在,我有这个(简体):
1 2 3 4 | char line[100 + 1]; while (fgets(line, sizeof(line), tsin) != NULL) { // tsin is FILE* input ... //doing stuff with line } |
具体来说,我想知道是否还有其他条件作为条件? 从文本文件到"行"的解析是否必须在while条件下进行?
根据参考
On success, the function returns str.
If the end-of-file is encountered while attempting to read a character, the eof indicator is
set (feof). If this happens before any characters could be read, the
pointer returned is a null pointer (and the contents of str remain
unchanged). If a read error occurs, the error indicator (ferror) is
set and a null pointer is also returned (but the contents pointed by
str may have changed).
因此,检查返回的值是否为
您所做的事情100%可以,但是您也可以简单地将
1 2 3 4 5 | char line[100 + 1] =""; /* initialize all to 0 ('\0') */ while (fgets(line, sizeof(line), tsin)) { /* tsin is FILE* input */ /* ... doing stuff with line */ } |
为什么?
(注意:您必须确保
我有同样的问题,我以这种方式解决了
1 2 3 |