2013-02-07 25 views
3

是不是可以讀取小於緩衝區大小的文件中剩餘的字節?C - 如果緩衝區較大,如何處理文件的最後部分?

char * buffer = (char *)malloc(size); 
FILE * fp = fopen(filename, "rb"); 

while(fread(buffer, size, 1, fp)){ 
    // do something 
} 

我們假設size是4,文件大小是17字節。我認爲即使留在文件中的字節小於緩衝區大小,fread也可以處理最後一次操作,但顯然它只是在while循環結束時不讀取最後一個字節。

我試圖使用較低的系統調用read(),但由於某種原因我無法讀取任何字節。

如果fread無法處理小於緩衝區大小的字節的最後部分,該怎麼辦?

回答

4

是的,把你的參數。

而不是請求size字節的一個塊,您應該請求size塊的1個字節。然後,該函數將返回有多少塊(字節)能夠閱讀:

int nread; 
while(0 < (nread = fread(buffer, 1, size, fp))) ... 
+0

啊我濫用了這兩個論點......!謝謝 – REALFREE

0

嘗試使用「人的fread」

它清晰地標註下列內容本身回答您的問題:

SYNOPSIS 
size_t fread(void *ptr, size_t size, size_t nitems, FILE *stream); 

DESCRIPTION 
    fread() copies, into an array pointed to by ptr, up to nitems items of 
    data from the named input stream, where an item of data is a sequence 
    of bytes (not necessarily terminated by a null byte) of length size. 
    fread() stops appending bytes if an end-of-file or error condition is 
    encountered while reading stream, or if nitems items have been read. 
    fread() leaves the file pointer in stream, if defined, pointing to the 
    byte following the last byte read if there is one. 

    The argument size is typically sizeof(*ptr) where the pseudo-function 
    sizeof specifies the length of an item pointed to by ptr. 

RETURN VALUE 
    fread(), return the number of items read.If size or nitems is 0, no 
    characters are read or written and 0 is returned. 

    The value returned will be less than nitems only if a read error or 
    end-of-file is encountered. The ferror() or feof() functions must be 
    used to distinguish between an error condition and an end-of-file 
    condition.