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?
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 ..
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