读取文件为字节数组
我有一个编码霍夫曼算法的任务。 我把整个问题整理在脑海中,但我在文件处理方面遇到了一些麻烦。
问题是:算法应该压缩任何类型的文件。
我的解决方案:将文件读取为字节数组,然后对每个字节使用int array[256]={0}
,得到它对应的值并增加array[n]
。 如果我没说清楚,请告诉我。
所以,我做了很多研究,但不明白如何从任何类型的文件中获取字节以及如何处理它们。
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
现在你有一个包含文件内容的字节数组。
如何尝试二进制文件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]++; }
或者其他什么!