我想了解一個文件位置指示器在從文件中讀取一些字節後如何移動。我有一個名爲「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指針) –