2010-02-21 56 views
6

我想將文件從指定的庫複製到當前目錄。我可以完美地複製文本文件。任何其他文件都會損壞。程序在它應該之前檢測到一個feof。如何讀取c中的二進制文件? (視頻,圖像或文本)

#include <stdio.h> 

int BUFFER_SIZE = 1024; 
FILE *source; 
FILE *destination; 
int n; 
int count = 0; 
int written = 0; 

int main() { 
    unsigned char buffer[BUFFER_SIZE]; 

    source = fopen("./library/rfc1350.txt", "r"); 

    if (source) { 
     destination = fopen("rfc1350.txt", "w"); 

     while (!feof(source)) { 
      n = fread(buffer, 1, BUFFER_SIZE, source); 
      count += n; 
      printf("n = %d\n", n); 
      fwrite(buffer, 1, n, destination); 
     } 
     printf("%d bytes read from library.\n", count); 
    } else { 
     printf("fail\n"); 
    } 

    fclose(source); 
    fclose(destination); 

    return 0; 
} 

回答

16

你在Windows機器上嗎?嘗試在fopen的調用中向模式字符串添加「b」。

從人的fopen(3):

模式串還可以包括字母「b」或者作爲最後一個字符或如上述任何兩個字符的字符串的字符之間的字符。這完全是爲了與C89兼容而沒有任何影響;在所有符合POSIX標準的系統(包括Linux)上忽略'b'。 (其他系統可能會以不同的方式處理文本文件和二進制 文件,如果對二進制文件執行I/O 並添加'b'可能是一個好主意,並且希望您的程序可以移植到非Unix環境。 )
+0

修正了它。謝謝。 –

4

你需要指定"b"選項fopen

source = fopen("./library/rfc1350.txt", "rb"); 
... 
destination = fopen("rfc1350.txt", "wb"); 

沒有它,該文件中的文本("t")模式打開,這將導致的最終行字符翻譯。

2

您需要以二進制格式打開文件而不是文本格式。在您致電fopen時,分別使用"rb""wb"而不是"r""w"