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

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

问题描述

我有一个很难与一个do-whil​​e循环,是应该停止
当我们到达文件的结尾。这里的循环code:

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?

推荐答案

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

I would change your loop and logic to use this:

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

    /* do things */

}

在与fgets()试图读到文件的结尾,它会返回NULL,你会跳出循环。您仍然可以继续使用通过和你的其他标志/逻辑,但你检查的情况会略有不同。

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天全站免登陆