Accessing memory buffer after fread()

Go To StackoverFlow.com

1

I'm confused as to how fread() is used. Below is an example from cplusplus.com

/* fread example: read a complete file */
#include <stdio.h>
#include <stdlib.h>

int main () {
  FILE * pFile;
  long lSize;
  char * buffer;
  size_t result;

  pFile = fopen ( "myfile.bin" , "rb" );
  if (pFile==NULL) {fputs ("File error",stderr); exit (1);}

  // obtain file size:
  fseek (pFile , 0 , SEEK_END);
  lSize = ftell (pFile);
  rewind (pFile);

  // allocate memory to contain the whole file:
  buffer = (char*) malloc (sizeof(char)*lSize);
  if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}

  // copy the file into the buffer:
  result = fread (buffer,1,lSize,pFile);
  if (result != lSize) {fputs ("Reading error",stderr); exit (3);}

  /* the whole file is now loaded in the memory buffer. */

  // terminate
  fclose (pFile);
  free (buffer);
  return 0;
}

Let's say that I don't use fclose() just yet. Can I now just treat buffer as an array and access elements like buffer[i]? Or do I have to do something else?

2012-04-05 23:23
by Tianxiang Xiong


3

Of course you can, when you call fread data is actually copied inside the buffer. You can safely close the file and do whatever you want with the buffer itself.

If you are asking if you can access buffer by modifying it and the original file then answer is no, you will have to write file back again by opening it in write mode and using fwrite.

If you have a binary file which has for example 2 float numbers, 1 int and a 16 character string you can easily define a struct

struct MyData
{
  float f1;
  float f2;
  int i1;
  char string[16];
};

and read it directly with:

struct MyData buffer;
fread(&buffer, 1, sizeof(struct MyData), file);
.. buffer.f1 ..
2012-04-05 23:25
by Jack
When I'm reading in a binary file, what will be the type of each element? I have a feeling that in this case they're all char's. Must they all be of the same type? Because I've got some doubles and some hex values together. Thanks for your answer - Tianxiang Xiong 2012-04-05 23:32
The good thing about binary files is that if you know the exact layout you won't have any problem, you can define a struct that has the same layout of binary data inside the file and (if endianness is correct) directly have the data ready to be used. Check my edit - Jack 2012-04-05 23:34
Ads