Read a file as byte array [closed]

2019-01-23 04:50发布

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 ANY kind 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 n corresponding value and increment the array[n]. If I didn't make it clear, let me know.

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.

2条回答
孤傲高冷的网名
2楼-- · 2019-01-23 05:03

How about trying binary 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]++;
  }

Or something along the lines!!

查看更多
Bombasti
3楼-- · 2019-01-23 05:09
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

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

查看更多
登录 后发表回答