C语言 将文件读取为字节数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22059189/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 10:49:28  来源:igfitidea点击:

Read a file as byte array

cfile-iohuffman-code

提问by alissonlacerda

I have an assignment for coding a Huffman algorithm. I have the whole problem organized in my head, but I'm having some trouble with file handling.

我有一个编写霍夫曼算法的作业。我脑子里想通了整个问题,但是我在处理文件时遇到了一些麻烦。

The problem is: the algorithm is supposed to compress ANYkind of file.

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

My solution: read the file as a byte array, then with an int array[256]={0}for each byte, get it's int ncorresponding value and increment the array[n]. If I didn't make it clear, let me know.

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

So, I've done lots of researching, but don't understand how to get bytes from ANY kind of file and how to handle them.

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

回答by user1274193

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 * sizeof(char)); // Enough memory for the file
fread(buffer, filelen, 1, fileptr); // Read in the entire file
fclose(fileptr); // Close the file

Now you have an array of bytes containing the file's contents.

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

回答by Suryavanshi

How about trying binary file IO:

试试二进制文件 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]++;
  }

Or something along the lines!!

或者类似的东西!!