2014-02-27 241 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]++; 
    } 

或沿着线的东西!

相关问题