Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading binary file in C (in chunks)

Tags:

c

I'm not good at C and I'm trying to do something simple. I want to open a binary file, read blocks of 1024 bytes of data and dump into a buffer, process the buffer, read another 1024 byes of data and keep doing this until EOF. I know how / what I want to do with the buffer, but it's the loop part and file I/O I keep getting stuck on.

PSEUDO code:

FILE *file;
unsigned char * buffer[1024];

fopen(myfile, "rb");

while (!EOF)
{
  fread(buffer, 1024);
  //do my processing with buffer;
  //read next 1024 bytes in file, etc.... until end
}
like image 597
Mike Avatar asked Jan 28 '15 16:01

Mike


People also ask

How do I read a binary file in C?

Use the fread Function to Read Binary File in C FILE* streams are retrieved by the fopen function, which takes the file path as the string constant and the mode to open them. The mode of the file specifies whether to open a file for reading, writing or appending.

What is chunk in C?

Chunks are normally 4096 bytes long unless you specify a different chunk size. The chunk size includes 8 bytes of overhead that are not actually used for storing objects. Regardless of the specified size, longer chunks will be allocated when necessary for long objects.

Why are binary files faster and easier for a program to read and write than text files?

Binary files also usually have faster read and write times than text files, because a binary image of the record is stored directly from memory to disk (or vice versa). In a text file, everything has to be converted back and forth to text, and this takes time.

Which methods are used to write and read into from a binary file?

The BinaryReader and BinaryWriter classes are used for reading from and writing to a binary file.


1 Answers

fread() returns the number of bytes read. You can loop until that's 0.

FILE *file = NULL;
unsigned char buffer[1024];  // array of bytes, not pointers-to-bytes
size_t bytesRead = 0;

file = fopen(myfile, "rb");   

if (file != NULL)    
{
  // read up to sizeof(buffer) bytes
  while ((bytesRead = fread(buffer, 1, sizeof(buffer), file)) > 0)
  {
    // process bytesRead worth of data in buffer
  }
}
like image 155
Paul Roub Avatar answered Oct 11 '22 12:10

Paul Roub