1

私は次のプログラムを持っています

#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() 関数呼び出しから得られるのと同じ結果が期待できます。

4

1 に答える 1

1

私のコンパイラは、「xxc.c:33:5: 警告: 関数 'lseek' の暗黙の宣言 [-Wimplicit-function-declaration]」と言います。

これは、2 番目の引数が整数 (おそらく 32 ビット) であると見なされることを意味しますが、定義は実際には型 "off_t" 用であり、Linux または Windows ではより長い 64 ビット整数になります。

これは、与えているオフセットが非常に大きく、テストファイルの終わりをはるかに超えている可能性が高いことを意味します。

マニュアルによると、 lseek() にはヘッダーが必要です。

   #include <sys/types.h>
   #include <unistd.h>
于 2015-02-07T14:30:59.040 に答える