【问题标题】:sendfile doesn't copy file contentssendfile 不复制文件内容
【发布时间】:2012-12-12 20:19:01
【问题描述】:

我创建文件1.txt2.txt,并将一些内容写入1.txt
然后我用下面的代码,想把内容复制到2.txt.
但它不起作用。 2.txt 里面什么都没有。

你能解释一下我的错误吗?

int main()
{
    int fd1 = open("1.txt",O_RDWR);
    int fd2 = open("2.txt",O_RDWR);          
    struct stat stat_buf ;
    fstat(fd1,&stat_buf);
    ssize_t size = sendfile(fd1,fd2,0,stat_buf.st_size);
    cout<<"fd1 size:"<<stat_buf.st_size<<endl; //output 41
    cout<<strerror(errno)<<endl; //output success

    close(fd1);
    close(fd2);
    return 0;
}

【问题讨论】:

  • 这被标记为“c”,但显然使用的是 C++ 流。不要这样做。
  • 因为我使用的是 linux C API --"sendfile",所以我标记了 "C"。我会注意这一点。谢谢!

标签: c++ linux system-calls sendfile


【解决方案1】:

根据sendfile 原型,您要写入的 fd 应该是第一个参数,而从中读取的 fd 应该是第二个参数。但是,您以完全相反的方式使用它。

所以,你的 sendfile 语句应该如下:

ssize_t size = sendfile(fd2,fd1,0,stat_buf.st_size);

【讨论】:

    【解决方案2】:

    根据man,签名是

    ssize_t sendfile(int out_fd, int in_fd, off_t *offset, size_t count);

    所以,第一个参数是要写入的文件描述符,第二个参数是要读取的文件描述符。

    所以,你的电话应该是:

    ssize_t size = sendfile(fd2,fd1,0,stat_buf.st_size);

    【讨论】:

    • 你应该颠倒sendfile中的fd2fd1的顺序。
    • 如果你使用有意义的变量名会更清楚。例如。 in_file, out_file 会更容易发现它们是错误的。
    猜你喜欢
    • 2019-01-15
    • 1970-01-01
    • 2011-07-21
    • 2021-06-29
    • 1970-01-01
    • 2011-01-16
    • 2015-04-02
    • 1970-01-01
    • 2021-12-16
    相关资源
    最近更新 更多