代码之家  ›  专栏  ›  技术社区  ›  peachykeen

为什么fgetc会将文件偏移量放在文件末尾?

c
  •  1
  • peachykeen  · 技术社区  · 4 年前

    我有一个简单的测试程序 fgetc() 从文件流中读取字符 lseek() 读取文件偏移量。看起来是这样的:

    #include <stdio.h>
    #include <unistd.h>
    #include <sys/types.h>
    #include <sys/stat.h>
    #include <fcntl.h>
    
    int main() {
        char buf[] = "hello world";
        FILE *f;
        int fd;
    
        fd = open("test.txt", O_RDWR | O_CREAT | O_TRUNC, 0600);
        write(fd, buf, sizeof(buf));
        lseek(fd, 0, SEEK_SET);
    
        f = fdopen(fd, "r");
    
        printf("%c\n", fgetc(f));
        printf("%d\n", lseek(fd, 0, SEEK_CUR));
    }
    

    h
    12
    

    的返回值 fgetc(f) , h ,对我来说很有意义。但为什么要将文件偏移量重新定位到文件的末尾呢?为什么不呢 lseek(fd, 0, SEEK_CUR) 给我一个?

    如果我重复第一个print语句,它将按预期工作并打印 e 然后是一个 l 等。

    我在报纸上没看到有人提到这种奇怪的行为 man 第页。

    1 回复  |  直到 4 年前
        1
  •  4
  •   Nate Eldredge    4 年前

    stdio函数如下 fgetc read() 一个大的块放入缓冲区,然后在连续调用时从缓冲区返回字符。

    fgetc() lseek 返回文件末尾的位置。

    如果您想得到一个考虑到缓冲区中仍然存在的内容的文件位置,请使用 fseek()