Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read a file as byte array [closed]

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.

like image 578
alissonlacerda Avatar asked Feb 27 '14 04:02

alissonlacerda


People also ask

Does readAllBytes close the stream?

readAllBytes. Reads all remaining bytes from the input stream. This method blocks until all remaining bytes have been read and end of stream is detected, or an exception is thrown. This method does not close the input stream.

How do you turn an object into a Bytearray?

Write the contents of the object to the output stream using the writeObject() method of the ObjectOutputStream class. Flush the contents to the stream using the flush() method. Finally, convert the contents of the ByteArrayOutputStream to a byte array using the toByteArray() method.


1 Answers

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.

like image 176
user1274193 Avatar answered Sep 20 '22 08:09

user1274193