2015-02-07 60 views
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()函數調用相同的結果。

+1

試着用'-Wall'編譯。你似乎錯過了'lseek'的原型('#include '),這可能是你的問題。 – 2015-02-07 14:25:42

+0

確實如此。在你的平臺上(x86-64?)可能'off_t'比'int'寬,所以隱含的'lseek(int,int,int)'聲明將是不兼容的。我可以在沒有缺少'#include'的情況下複製它,但不能使用它。 – Wintermute 2015-02-07 14:30:02

回答

1

我的編譯器說「xxc.c:33:5:警告:的函數‘lseek的’[-Wimplicit函數聲明]隱式聲明」

這意味着,第二個參數將被認爲是一個整數(可能是32位),但定義實際上是針對類型「off_t」,在Linux或Windows上將是更長的64位整數。

這意味着你給它的偏移很可能會非常大並且超過你的測試文件的末尾。

手冊上說,對於lseek的(),你需要的標題:

#include <sys/types.h> 
    #include <unistd.h>