2015-02-06 21 views
1

對於一個賦值,我應該創建兩種方法:方法一將read()write()輸入到一個空輸出文件,一次一個字節(緩慢)。如何在C中使用BUFSIZ的讀寫方式

另一種方法將改爲使用char buf[BUFSIZ];其中BUFSIZ來自<stdio.h>。我們應該read()write()BUFSIZ這將使事情快很多。

我們測試每種方法的輸入文件只是一個linux字典(/dict/linux.words)。

我已經正確實施了方法之一,我一次只對一個字符調用read()write(),將輸入文件複製到輸出文件。雖然速度很慢,但至少可以複製一切。

我給這家代碼如下所示:

// assume we have a valid, opened fd_in and fd_out file. 
char buf; 
while(read(fd_in, buf, 1) != 0) 
    write(fd_out, buf, 1); 

對於方法二然而,當我使用BUFSIZ,我不能給每一個進入輸出傳輸文件。它在z條目中失敗,並且不再寫入。

所以,我第一次嘗試:

// assume we have a valid, opened fd_in and fd_out file 
char buf[BUFSIZ]; 
while(read(fd_in, buf, BUFSIZ) != 0) 
    write(fd_out, buf, BUFSIZ); 

不起作用。

據我所知,read()將返回讀取的字節數或0,如果它在文件的末尾。我遇到的問題是瞭解如何將read()BUFSIZ進行比較,然後在停止的地方循環並開始read(),直到達到文件的實際末尾。

+0

...'結果=讀(..);如果(結果 usr2564301 2015-02-06 10:54:09

+0

@Jongware現在呢:/因爲midterms/projects已經連續兩天了,所以我的大腦很油膩:( – Alex 2015-02-06 11:02:07

回答

3

由於您的文件很可能不會是BUFSIZ的確切倍數,因此您需要檢查讀取的實際字節數,以便最後一個塊可以正確寫入。

char buf[BUFSIZ]; 
ssize_t n; 
while((n = read(fd_in, buf, BUFSIZ)) > 0) 
    write(fd_out, buf, n); 
+0

謝謝你的幫助!這很有道理。 – Alex 2015-02-06 11:01:03

+0

請注意,你的文件可以在大多數情況下可能大於BUFSIZ,所以你將不得不做多個讀取 – Pandrei 2015-02-06 12:16:51

+0

@Pandrei:是的,這就是讀寫調用嵌入在while循環中的原因。 – 2015-02-06 13:25:58

0
this code: 

// assume we have a valid, opened fd_in and fd_out file 
char buf[BUFSIZ]; 
while(read(fd_in, buf, BUFSIZ) != 0) 
    write(fd_out, buf, BUFSIZ); 

leaves much to be desired, 
does not handle a short remaining char count at the end of the file, 
does not handle errors, etc. 

a much better code block would be: 

// assume we have a valid, opened fd_in and fd_out file 
char buf[BUFSIZ]; 
int readCount; // number of bytes read 
int writeCount; // number of bytes written 

while(1) 
{ 
    if(0 > (readCount = read(fd_in, buf, BUFSIZ))) 
    { // then, read failed 
     perror("read failed"); 
     exit(EXIT_FAILURE); 
    } 

    // implied else, read successful 

    if(0 == readCount) 
    { // then assume end of file 
     break; // exit while loop 
    } 

    // implied else, readCount > 0 

    if(readCount != (writeCount = write(fd_out, buf, readCount))) 
    { // then, error occurred 
     perror("write failed"); 
     exit(EXIT_FAILURE); 
    } 

    // implied else, write successful 
} // end while 

注:我不包括輸入/​​輸出文件的語句 的每次調用前關閉退出(),但是,這並不需要添加