2012-12-27 44 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);