假设我有一个使用 POSIX 扩展的 C 程序,有一个
FILE *fp
及其文件描述符 int fd
。我可以假设fd
(根据lseek(fd, 0, SEEK_CUR)
)的“文件位置”应该与fp
(根据ftell(fp)
)的“文件位置”匹配吗?我所说的“假设”是指“POSIX 要求......”
我认为可以肯定地说,您可以假设在某些情况下它们不匹配。
最明显的情况是预读:stdio 通常读取几千字节的块,无论应用程序需要多少字节。然后,
ftell()
将根据应用程序代码读取的数量来告诉位置,而lseek()
将根据从操作系统读取的stdio的数量来告诉位置。
尝试这样的事情:
$ cat > seek.c <<'EOF'
#include <stdio.h>
#include <unistd.h>
char buf[123];
int main(void) {
int fd = fileno(stdin);
fread(buf, 12, 3, stdin);
long pos1 = ftell(stdin);
long pos2 = lseek(fd, 0, SEEK_CUR);
printf("pos1: %ld pos2: %ld\n", pos1, pos2);
return 0;
}
EOF
$ gcc -Wall -o seek seek.c
$ ./seek < dummyfile
pos1: 36 pos2: 4096