首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >函数在调用lseek()时不读取任何字节。

函数在调用lseek()时不读取任何字节。
EN

Stack Overflow用户
提问于 2015-02-07 14:17:09
回答 1查看 768关注 0票数 1

我有以下程序

代码语言:javascript
复制
#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中的以下内容:

代码语言:javascript
复制
This is a test.
A second test line.

程序的输出:

代码语言:javascript
复制
before lseek: This is a 
 readBytes: 10
after lseek: 
 readBytes: 0

我不知道为什么在after ()调用之后,read()函数不读取任何字节。原因是什么?我希望得到与第一个read()函数调用相同的结果。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-02-07 14:30:59

我的编译器说:"xxc.c:33:5:警告:函数的隐式声明“

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

这意味着您要给它的偏移量很可能非常大,并且可能远远超过您的测试文件的末尾。

手册中说,对于lseek(),您需要标题:

代码语言:javascript
复制
   #include <sys/types.h>
   #include <unistd.h>
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28383181

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档