简体   繁体   English

使用C中的fgets读取文本文件直到EOF

[英]Reading text-file until EOF using fgets in C

what is the correct way to read a text file until EOF using fgets in C? 在C中使用fgets读取文本文件直到EOF的正确方法是什么? Now I have this (simplified): 现在我有了这个(简化):

char line[100 + 1];
while (fgets(line, sizeof(line), tsin) != NULL) { // tsin is FILE* input
   ... //doing stuff with line
}

Specifically I'm wondering if there should be something else as the while-condition? 具体来说,我想知道是否应该有其他东西作为时间条件? Does the parsing from the text-file to "line" have to be carried out in the while-condition? 从文本文件到“行”的解析是否必须在while条件下执行?

According to the reference 根据参考

On success, the function returns str . 成功时,函数返回str If the end-of-file is encountered while attempting to read a character, the eof indicator is set (feof). 如果在尝试读取字符时遇到文件结尾,则设置eof指示符(feof)。 If this happens before any characters could be read, the pointer returned is a null pointer (and the contents of str remain unchanged). 如果在读取任何字符之前发生这种情况,则返回的指针是空指针 (并且str的内容保持不变)。 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). 如果发生读取错误,则设置错误指示符(ferror)并返回空指针(但str指向的内容可能已更改)。

So checking the returned value whether it is NULL is enough. 因此检查返回值是否为NULL就足够了。 Also the parsing goes into the while-body. 解析也进入了while-body。

What you have done is 100% OK, but you can also simply rely on the return of fgets as the test itself, eg 你所做的是100%好,但你也可以简单地依靠fgets的返回作为测试本身,例如

char line[100 + 1] = "";  /* initialize all to 0 ('\0') */

while (fgets(line, sizeof(line), tsin)) { /* tsin is FILE* input */
    /* ... doing stuff with line */
}

Why? 为什么? fgets will return a pointer to line on success, or NULL on failure (for whatever reason). fgets将在成功时返回指向line的指针,或在失败时返回NULL (无论出于何种原因)。 A valid pointer will test true and, of course, NULL will test false . 有效的指针将测试为true ,当然, NULL将测试为false

( note: you must insure that line is a character array declared in scope to use sizeof line as the length. If line is simply a pointer to an array, then you are only reading sizeof (char *) characters) 注意:你必须确保该line在作用域中声明的字符数组 ,使用sizeof line作为长度。如果line只是指向数组的指针,那么你只读取sizeof (char *)字符)


i had the same problem and i solved it in this way 我有同样的问题,我以这种方式解决了它

while (fgets(line, sizeof(line), tsin) != 0) { //get an int value
   ... //doing stuff with line
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM