一个简单的sendfile程序,但不起作用

时间:2011-10-05 09:23:16

标签: c sendfile

#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <sys/sendfile.h>
#include <sys/stat.h>
#include <fcntl.h>

int main(){
    int fd1,fd2,rc;
    off_t offset = 0;
    struct stat stat_buf;

    fd1=open("./hello.txt",O_RDONLY); //read only
    fd2=open("../",O_RDWR);           //both read and write
    fstat(fd1, &stat_buf);            //get the size of hello.txt
    printf("file size: %d\n",(int)stat_buf.st_size);
    rc=sendfile (fd2, fd1, &offset, stat_buf.st_size);
}

正如你所看到的,这是一个非常简单的程序。但是我在...中找不到hello.txt 我的目标是看看如果我输入任何数字,10表示会发生什么,而不是可能是数百字节的st_size。

编辑:

感谢您的回答。好吧,我按照你的建议改变了

 fd2=open("../",O_RDWR);

 fd2=open("../hello.txt",O_RDWR);

另外,我检查了fstat和sendfile的返回值,一切正常。

但问题仍然存在。

3 个答案:

答案 0 :(得分:2)

您需要在第二个open中指定文件名,而不仅仅是目录名。

请务必检查所有这些功能的返回值,包括fstat

答案 1 :(得分:2)

您是否尝试过fd2 = open("../hello.txt",O_RDWR);

答案 2 :(得分:0)

1&GT;

  fd1=open("./hello.txt",O_RDONLY); //read only
  fd2=open("../",O_RDWR);           //both read and write

替换为

 fd1=open("../hello.txt",O_RDONLY); //read only
  fd2=open("../your_file_name",O_RDWR);         

2 - ;

 fstat(fd1, &stat_buf); 

将在stat_buf中填写与fd1文件相关的一些信息。此处该文件的大小也在该结构中使用st_size元素返回。

现在在

 rc=sendfile (fd2, fd1, &offset, stat_buf.st_size);

将在fd2文件上发送总stat_buf.st_size个字节。如果你在这里写10,那么fd2中只有10个字节。

相关问题