C: feof 的奇怪行为

标签 c fseek feof

<分区>

我是 C 的新手。我偶然发现了 feof 的某些我无法解释的行为。具体在下面的代码中,我创建了一个文件,将一个字节的信息写入其中,然后关闭并再次打开它,读取信息(我的 1 个字节)直到到达 EOF,然后移动当前位置将文件指针移动 0 字节(即根本不更改当前位置),突然间我不再位于 EOF 处。怎么会?

#include <stdio.h>
#include <stdint.h>
typedef uint8_t BYTE;

int main(void) {
    FILE* f = fopen("myfile.txt","w");
    BYTE b = 0x0000;
    fwrite(&b,1,1,f);
    fclose(f);
    f = fopen("myfile.txt","r");
    while (!feof(f)){
        fread(&b,1,1,f);
    }
    printf("We have reached EOF: %i \n",feof(f));
    fseek(f,0,SEEK_CUR);
    printf("We have reached EOF: %i \n",feof(f));
} 

输出

We have reached EOF: 1 
We have reached EOF: 0 

最佳答案

来自fseek文档:

The end-of-file internal indicator of the stream is cleared after a successful call to this function, and all effects from previous calls to ungetc on this stream are dropped.

关于C: feof 的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47979950/

相关文章:

c - 如何在单独的线程中更新 GTK+ GUI 的一部分,该线程不断从另一个进程读取数据?

c++ - 如何使用 fseek() 进入一行的开头

c - 如何找到 wav 文件的字节?

c - 为什么“while(!feof(file))”总是错误的?

c - 我在 C 中创建 strcat 函数的代码函数有什么问题?

c - 内存故障 (CoreDump) - 在 sprintf 中使用 strstr 函数时

c - 嵌套结构变量初始化

c - fread fseek 仅在 C 中的结构成员

c - 如何使用feof(FILE *f)?

c - 使用 feof() 从文件读取并退出循环