2012-12-27 43 views
5

我创建文件1.txt2.txt并将一些内容写入1.txt
然后我使用下面的代码,并要复制内容到2.txt
但它不起作用。 2.txt中没有任何内容。sendfile不复制文件内容

你能解释我的错误吗?

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

这标记 'C',但很明显,使用C++流。不要这样做。 – unwind

+0

已移至C++。 ;) –

+0

因为我使用linux C API - “sendfile”,所以我taaged“C”。我会关注这一点,谢谢! – Tengchao

回答

5

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

+0

你应该在'sendfile'中改变'fd2'和'fd1'的顺序。 – banuj

+1

如果使用有意义的变量名,它会更清晰。例如。 in_file,out_file会更容易发现它们是错误的。 –

+0

行,这么简单的错误,谢谢! – Tengchao

0

sendfile原型中,FD你想写应该是第一个参数,FD从其中一个读应该是第二个参数到。但是,你已经用完全相反的方式。

所以,你的sendfile的说法应该是如下:

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