【问题标题】:A simple sendfile program, but not works一个简单的 sendfile 程序,但不起作用
【发布时间】:2011-12-01 07:53:21
【问题描述】:
#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的返回值,一切正常。

但问题还是一样。

【问题讨论】:

  • 您是否检查过 hello.txt 在上一个文件夹中是否存在?
  • 嗨@Mr.32,你的意思是存在吗?嗯,结果显示不会在上一个文件夹中创建hello.txt。
  • 在上一个文件夹中应该有你要打开的 hello.txt..
  • 好吧,我也尝试过手动或仅使用 O_RDWR|O_CREAT 创建一个 hello.txt。所以我可以在那里找到文件,但它只是一个空文件。

标签: c sendfile


【解决方案1】:

1>

  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);

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

【讨论】:

    【解决方案2】:

    你试过fd2 = open("../hello.txt",O_RDWR);吗?

    【讨论】:

    • 嗨@CharlesB,我听从了你的建议,但结果还是一样
    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-03
      • 1970-01-01
      • 1970-01-01
      • 2018-10-05
      • 1970-01-01
      • 1970-01-01
      • 2013-05-09
      相关资源
      最近更新 更多