我有以下程序
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
int main(int argc, char* argv[]) {
int fd;
char buffer[100];
// open notes file
fd = open("/var/testfile", O_RDONLY);
if(fd == -1) {
error("in main() while opening file for reading");
}
int readBytes = 0;
// read 10 bytes the first time
readBytes = read(fd, buffer, 10);
buffer[10] = 0;
printf("before lseek: %s\n readBytes: %d\n", buffer, readBytes);
// reset buffer
int i = 0;
for(i = 0; i < 10; i++) {
buffer[i] = 0;
}
// go back 10 bytes
lseek(fd, -10, SEEK_CUR);
// read bytes second time
readBytes = read(fd, buffer, 10);
buffer[10] = 0;
printf("after lseek: %s\n readBytes: %d\n", buffer, readBytes);
}
以及 /var/testfile 中的以下内容:
This is a test.
A second test line.
程序的输出:
before lseek: This is a
readBytes: 10
after lseek:
readBytes: 0
我不明白为什么在 lseek() 调用后 read() 函数不读取任何字节。这是什么原因?我希望得到与第一次 read() 函数调用相同的结果。