c - 从文件循环读取 - 无法使用 feof 或 getc 进入循环

标签 c file-io eof

所以这只是一个简单的文件循环读取,我似乎无法弄清楚出了什么问题。我已经尝试了多种方法,但我似乎无法通过循环。我已经尝试了很多方法来进入(最初使用 getc,但使用 getc 整个循环将被忽略。

出于某种原因,它只是不适合我。如下所示,程序一进入 while 条件就卡住。也许有人可以解释为什么会这样,因为文件指针应该指向文件的开头。文件“input.txt”只是一个简单的数据列表,我应该将其读入结构,然后传递给另一个函数以输入到我的数据结构中。

然而,我似乎无法使用其他功能。花了几个小时尝试解决这个问题的不同方法。我确信有一个我没有看到的明显解决方案。

void readWrite(char *inFile)
{
    FILE *fp;
    FILE *fpBin;
    char c;
    stuBucket temprec;
    long address;

    //open binary file to initialize hash file
    if ((fpBin = fopen(BINARYFILE, "w+b")) == NULL)
    {
        printf("Could not open binary file %s.\n", BINARYFILE);
        return;
    }
    fwrite(fpBin, sizeof(struct student), 50, fpBin); //Write entire hash table to disk
    if (fp = fopen(inFile, "r") == NULL)     //open text file to read in from
    {
        printf("Could not open input file %s.\n", inFile);
        return;
    }
    printf("Input File %s Open.\n", inFile);

下面while循环的问题

    while(!feof(fp))
    {
        printf("hello");
        fscanf(fp, "%d %s %s %f\n", temprec.stuID, temprec.lastName,
                                     temprec.firstName, &temprec.amount);
        writeRecord(temprec);
        insert(temprec, fpBin); //hash data to disk
        printf("insert done\n");
    }
    fclose(fp);
    fclose(fpBin);
}//end readFromFile

在被跳过时交替

c = getc(fp);
while(c != EOF)
{
    ungetc(c, fp);
    printf("hello");
    fscanf(fp, "%d %s %s %f\n", temprec.stuID, temprec.lastName,
                                 temprec.firstName, &temprec.amount);
    writeRecord(temprec);
    insert(temprec, fpBin); //hash data to disk
    printf("insert done\n");
    c = getc(fp);
}

input.txt 的内容

6745 SMITH ANNA 7769.87
5675 JOHNSON SHEILA 23.91
1235 WILLIAMS JANE 93.12
2341 JONES BARBARA 74.23
8624 BROWN YELENA 56.75
9162 DAVIS SUSAN 902.34
7146 MILLER ALISON 8934.12
2328 WILSON ROYCE 123.09
1622 MOORE TONI 83.65
1832 TAYLOR JOAN 293.18
3271 GARCIA ROBERT 43.72
4717 MARTINEZ JHON 85.11
9345 ROBINSON ANDRE 15.67
1623 CLARK VICTOR 83.45
5673 HALL MARC 93.13
6275 ALLEN RAY 958.34
5392 HERNANDEZ MICHAEL 23.45

最佳答案

您的一个问题是:

if (fp = fopen(inFile, "r") == NULL)

它(当然)应该是:

if ((fp = fopen(inFile, "r")) == NULL)

然后这与您打开二进制文件的行相匹配。

关于c - 从文件循环读取 - 无法使用 feof 或 getc 进入循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23726896/

相关文章:

ios - 在 Objective C 中动态设置 C 结构数组的大小?

c++ - 如何从 C++ 文件中读取字符串和相应的 int?

javascript - 转换为文件对象时的 Base64 图像有一个奇怪的名字

java - 在 Java 中使用 Zip 和 GZip 文件

c - fseek 查找 EOF 字符

混淆缓冲区和 EOF 和 getchar

c - 为什么 Ctrl-Z 不触发 EOF?

c - 打印参数的 Oneliner C

c - getchar 从命令行参数中读取

c - 如何计算流程的完成时间? - 最短剩余时间优先算法