如何使用 feof(FILE *f)?
我在 do-while 循环上遇到了困难,它应该停止 当我们到达文件末尾时。这是循环代码:
do {
if (pcompanyRow[0] != '#' && pass == 1) {
strtok(pcompanyRow, ":");
pcompanyName = strcpy(pcompanyName, strtok(NULL, ""));
pass = 2;
fgets(pcompanyRow, 1024, f);
}
if (pcompanyRow[0] != '#' && pass == 2) {
strtok(pcompanyRow, ":");
pcompanySMSPrice = strcpy(pcompanySMSPrice, strtok(NULL , ""));
pass = 3;
fgets(pcompanyRow, 1024 , f);
}
if (pcompanyRow[0] != '#' && pass == 3) {
strtok(pcompanyRow, ":");
pcompanyMMSPrice = strcpy(pcompanyMMSPrice, strtok(NULL, ""));
pass = 4;
fgets(pcompanyRow, 1024, f);
}
if (pass == 4) {
AppendCompanyNode(pcompanyList, pcompanyName, pcompanySMSPrice, pcompanyMMSPrice);
pass = 1;
}
} while (!feof(f));
使用调试器运行后,我注意到我遇到的所有崩溃问题都是因为即使它到达整行,它也不会退出此循环。
应该怎样写才能正确呢?
I'm having a hard time with a do-while loop, that is supposed to stop
when we reach the end of the file. Here's the loop code:
do {
if (pcompanyRow[0] != '#' && pass == 1) {
strtok(pcompanyRow, ":");
pcompanyName = strcpy(pcompanyName, strtok(NULL, ""));
pass = 2;
fgets(pcompanyRow, 1024, f);
}
if (pcompanyRow[0] != '#' && pass == 2) {
strtok(pcompanyRow, ":");
pcompanySMSPrice = strcpy(pcompanySMSPrice, strtok(NULL , ""));
pass = 3;
fgets(pcompanyRow, 1024 , f);
}
if (pcompanyRow[0] != '#' && pass == 3) {
strtok(pcompanyRow, ":");
pcompanyMMSPrice = strcpy(pcompanyMMSPrice, strtok(NULL, ""));
pass = 4;
fgets(pcompanyRow, 1024, f);
}
if (pass == 4) {
AppendCompanyNode(pcompanyList, pcompanyName, pcompanySMSPrice, pcompanyMMSPrice);
pass = 1;
}
} while (!feof(f));
After running with the debugger, I noticed that all the crash problems I have are because it doesn't go out of this loop even when it reached the whole lines.
How should I write it correctly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
永远不应该使用 feof() 作为循环的退出指示符。 feof() 仅在读取文件末尾 (EOF) 后才为 TRUE,而不是在到达 EOF 时为 TRUE
来源 在这里。它还详细解释了问题以及如何解决它。
You should never use feof() as the exit indicator for a loop. feof() is TRUE only after the end of file (EOF) is read, not when EOF is reached
Source here. It also explains the problem in detail and how to fix it.
我会改变你的循环和逻辑来使用它:
当 fgets() 尝试读取文件末尾之后,它将返回 NULL 并且你将跳出循环。您仍然可以继续使用
pass
和其他标志/逻辑,但您检查的条件会略有不同。I would change your loop and logic to use this:
when fgets() attempts to read past the end of the file, it will return NULL and you'll break out of the loop. You can still continue to use
pass
and your other flags/logic, but the conditions you check for will be slightly different.我建议同时使用 fgets() 和 feof()。
文件中的最后一个字符串可能有 \n,也可能没有。如果您只使用 feof(),您可以跳过(丢失)最后一行。
I suggest use both fgets() and feof().
Last string in file might have \n or might not. If you use only feof(), you can skip (lost) last line.