我试图了解从文件中读取一些字节后文件位置指示器如何移动。我有一个名为“filename.dat”的文件,只有一行:“abcdefghijklmnopqrstuvwxyz”(不带引号)。
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main () {
int fd = open("filename.dat", O_RDONLY);
FILE* fp = fdopen(fd,"r");
printf("ftell(fp): %ld, errno = %d\n", ftell(fp), errno);
fseek(fp, 5, SEEK_SET); // advance 5 bytes from beginning of file
printf("file position indicator: %ld, errno = %d\n", ftell(fp), errno);
char buffer[100];
int result = read(fd, buffer, 4); // read 4 bytes
printf("result = %d, buffer = %s, errno = %d\n", result, buffer, errno);
printf("file position indicator: %ld, errno = %d\n", ftell(fp), errno);
fseek(fp, 3, SEEK_CUR); // advance 3 bytes
printf("file position indicator: %ld, errno = %d\n", ftell(fp), errno);
result = read(fd, buffer, 6); // read 6 bytes
printf("result = %d, buffer = %s, errno = %d\n", result, buffer, errno);
printf("file position indicator: %ld\n", ftell(fp));
close(fd);
return 0;
}
ftell(fp): 0, errno = 0
file position indicator: 5, errno = 0
result = 4, buffer = fghi, errno = 0
file position indicator: 5, errno = 0
file position indicator: 8, errno = 0
result = 0, buffer = fghi, errno = 0
file position indicator: 8
我不明白为什么我第二次尝试使用read
,我从文件中没有得到任何字节。另外,为什么当我使用从文件中读取内容时文件位置指示器不移动read
?在第二个fseek
,推进 4 个字节而不是 3 个也不起作用。有什么建议么?