1
我有以下程序POSIX閱讀()函數不讀取任何字節時lseek的()被調用
#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()函數調用相同的結果。
試着用'-Wall'編譯。你似乎錯過了'lseek'的原型('#include'),這可能是你的問題。 –
2015-02-07 14:25:42
確實如此。在你的平臺上(x86-64?)可能'off_t'比'int'寬,所以隱含的'lseek(int,int,int)'聲明將是不兼容的。我可以在沒有缺少'#include'的情況下複製它,但不能使用它。 – Wintermute 2015-02-07 14:30:02