如何使用 feof(FILE *f)? [英] How to use feof(FILE *f)?

查看:24
本文介绍了如何使用 feof(FILE *f)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 do-while 循环时遇到困难,应该停止当我们到达文件末尾时.这是循环代码:

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.

我该如何正确书写?

推荐答案

我会改变你的循环和逻辑来使用这个:

I would change your loop and logic to use this:

while (fgets(pcompanyRow, 1024, f) != NULL) {

    /* do things */

}

当 fgets() 尝试读取文件末尾时,它将返回 NULL 并且您将跳出循环.您仍然可以继续使用 pass 和您的其他标志/逻辑,但您检查的条件会略有不同.

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.

这篇关于如何使用 feof(FILE *f)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆