我想了解一个文件位置指示器在从文件中读取一些字节后如何移动。我有一个名为“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个也没有工作。有什么建议么?
相关的问题:?什么是文件描述符之间的差异,文件指针(http://stackoverflow.com/questions/2423628/whats-the-difference-between-a-file-descriptor-and -file指针) –