将文件读为字节数组

ali*_*rda 20 c file-io huffman-code

我有一个编码霍夫曼算法的任务.我把整个问题整理在脑海中,但我在文件处理方面遇到了一些麻烦.

问题是:该算法应该压缩任何类型的文件.

我的解决方案:将文件读取为字节数组,然后使用int array[256]={0}每个字节,获取int n相应的值并递增array[n].如果我没说清楚,请告诉我.

所以,我做了很多研究,但不明白如何从任何类型的文件中获取字节以及如何处理它们.

use*_*193 41

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
Run Code Online (Sandbox Code Playgroud)

现在你有一个包含文件内容的字节数组.

  • @Commander3000如果整个数组被视为一个字符串,那么 NULL 终止是有意义的,但OP询问如何读取二进制文件,即“任何”类型的文件。 (2认同)
  • 我只是注意到上面的答案也是通过在对malloc的调用中添加一个额外的字节来假设NULL终止,这不应该。如果二进制文件有N个字节,则不需要(N + 1)个字节为缓冲区分配内存。 (2认同)