简体   繁体   中英

sendfile doesn't copy file contents

I create files 1.txt 2.txt and write some content into 1.txt .
Then I use the code below and want to copy the content to 2.txt .
But it doesn't work. There is nothing in 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. But, you have used it the exactly opposite way.

So, you sendfile statement should be as below:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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