maxwellhertz
maxwellhertz

Reputation: 483

how to read a whole binary file at a time with C++

I have some binary data in a file. In order to read all the data, I did this:

// open the file
// ...
// now read the file
char data;
while (fread(&data, sizeof(char), 1, input) == 1) {
    // do something
}

Well, this worked finely but my teacher said I shouldn't read a file line by line because this would increase the amount of I/O. So now I need to read the whole binary file at a time. How can I do this? Could anyone help?

Upvotes: 0

Views: 1937

Answers (2)

Roshan M
Roshan M

Reputation: 601

unsigned long ReadFile(FILE *fp, unsigned char *Buffer, unsigned long BufferSize)
{
    return(fread(Buffer, 1, BufferSize, fp));
}

unsigned long CalculateFileSize(FILE *fp)
{
  unsigned long size;
  fseek (fp,0,SEEK_END);
  size= ftell (fp); 
  fseek (fp,0,SEEK_SET);
  if (size!=-1)
    {
      return size;
    }
  else
  return 0;
}

This function reads the file and stores it into a buffer, so accessing buffer reduce your IO time:

int main()
{
    FILE *fp = fopen("Path", "rb+");// i assume reading in binary mode
    unsigned long BufferSize = CalculateFileSize(fp);//Calculate total size of file
    unsigned char* Buffer = new unsigned char[BufferSize];// create the buffer of that size
    unsigned long  RetValue = ReadFile(fp, Buffer, BufferSize);
}

Upvotes: 2

Jorg B Jorge
Jorg B Jorge

Reputation: 1109

First notice that if you read the file to an 1 byte buffer (data variable in your code), your program will probably crash (if the filesize > 1). So, you need to allocate a buffer to read the file.

FILE *f = fopen(filepath, "rb+");
if (f)
{
    fseek(f, 0L, SEEK_END);
    long filesize = ftell(f); // get file size
    fseek(f, 0L ,SEEK_SET); //go back to the beginning
    char* buffer = new char[filesize]; // allocate the read buf
    fread(buffer, 1, filesize, f);
    fclose(f);

    // Do what you want with file data

    delete[] buffer;
}

Upvotes: 0

Related Questions