我有以下程序
#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: %sn readBytes: %dn", 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: %sn readBytes: %dn", 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()函数调用相同的结果。
我的编译器说"xxc.c:33:5:warning:函数'lseek'的隐式声明[-Wimplicit函数声明]"
这意味着第二个参数将被假设为一个整数(可能是32位),但定义实际上是针对类型"off_t"的,在Linux或Windows上,它将是一个更长的64位整数。
这意味着你给它的偏移量可能非常大,并且远远超过了测试文件的末尾。
手册上说,对于lseek(),您需要标题:
#include <sys/types.h>
#include <unistd.h>