简体   繁体   English

sendfile不复制文件内容

[英]sendfile doesn't copy file contents

I create files 1.txt 2.txt and write some content into 1.txt . 我创建文件1.txt 2.txt并将一些内容写入1.txt
Then I use the code below and want to copy the content to 2.txt . 然后,我使用下面的代码,并将内容复制到2.txt
But it doesn't work. 但这是行不通的。 There is nothing in 2.txt . 2.txt没有任何2.txt

Can you explain my mistake? 你能解释我的错误吗?

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

According to man , the signature is 人说 ,签名是

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

So, the first parameter is the file descriptor into you want to write and the second one is the file descriptor you want to read from. 因此,第一个参数是要写入的文件描述符,第二个参数是要从中读取的文件描述符。

So, your call should be: 因此,您的电话应该是:

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

As per sendfile prototype, the fd to which you want to write should be the first parameter and fd from which one reads should be the second parameter. 根据sendfile原型,要写入的fd应该是第一个参数,读取的fd应该是第二个参数。 But, you have used it the exactly opposite way. 但是,您使用了完全相反的方式。

So, you sendfile statement should be as below: 因此,您的sendfile语句应如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM