2014-02-27 242 views
14

我有一個編碼霍夫曼算法的任務。我把整個問題組織在我的腦海裏,但是我在文件處理方面遇到了一些麻煩。作爲字節數組讀取文件

問題是:該算法應該壓縮ANY種文件。

我的解決方案:將文件讀取爲一個字節數組,然後用一個int array[256]={0}爲每個字節,得到它的相應值int n並遞增array[n]。如果我沒有說清楚,請告訴我。

因此,我做了大量的研究,但不明白如何從任何類型的文件獲取字節以及如何處理它們。

+1

我敢肯定,你可以在這裏找到大量的例子... –

+0

我看到很多與這個主題有關的話題,但其中沒有一個對我來說很清楚。我這麼說,請在這裏鏈接一個。謝謝:) – alissonlacerda

+0

我看到了幾個問題......首先我將你的文件加載到一個char數組[]中。比一個普通的'fopen()'/'fread()'有什麼問題阻止它打開**任何**類文件?最後,請嘗試並報告它的錯誤。 – Sigismondo

回答

22
FILE *fileptr; 
char *buffer; 
long filelen; 

fileptr = fopen("myfile.txt", "rb"); // Open the file in binary mode 
fseek(fileptr, 0, SEEK_END);   // Jump to the end of the file 
filelen = ftell(fileptr);    // Get the current byte offset in the file 
rewind(fileptr);      // Jump back to the beginning of the file 

buffer = (char *)malloc((filelen+1)*sizeof(char)); // Enough memory for file + \0 
fread(buffer, filelen, 1, fileptr); // Read in the entire file 
fclose(fileptr); // Close the file 

現在你有一個包含文件內容的字節數組。

+0

非常感謝!我正在接近我想要的東西。我會學習更多並做一些測試。 – alissonlacerda

+0

不應該調用「buffer [filelen] ='\ 0';」在fclose之後? – Commander3000

+0

這給了我在fseek() – Singh

0

如何試圖二進制文件IO:

FILE *f=fopen("example.bin","rb"); 
    char c; 
    //loop for each byte to the end 
    { 
    size_t fread(&c, (size_t)1, (size_t) 1, f); 
    array[c]++; 
    } 

或沿着線的東西!

相關問題