Accessing memory buffer after fread()
Posted
by
xiongtx
on Stack Overflow
See other posts from Stack Overflow
or by xiongtx
Published on 2012-04-05T23:23:42Z
Indexed on
2012/04/05
23:29 UTC
Read the original article
Hit count: 259
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?
© Stack Overflow or respective owner