调用lseek()时,POSIX read()函数不读取任何字节

时间:2015-02-07 14:17:10

标签: c file-io 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 个答案:

答案 0 :(得分:1)

我的编译器说“xxc.c:33:5:警告:隐式声明函数'lseek'[-Wimplicit-function-declaration]”

这意味着第二个参数将被假定为一个整数(可能是32位),但该定义实际上是“off_t”类型,在Linux或Windows上它将是一个更长的64位整数。

这意味着您提供的偏移可能非常大并且远远超过了测试文件的末尾。

手册说对于lseek()你需要标题:

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