C examples for stdio.h:fread
function
<cstdio> <stdio.h>
Read block of data from stream
size_t fread ( void * ptr, size_t size, size_t count, FILE * stream );
Parameter | Description |
---|---|
ptr | Pointer to a block of memory with a size of at least (size*count) bytes |
size | Size, in bytes, of each element to be read. |
count | Number of elements, each one with a size of size bytes. |
stream | FILE object. |
The total number of elements successfully read is returned.
This code loads main.cpp into memory buffer.
#include <stdio.h> #include <stdlib.h> int main () {//w w w. j a va 2 s . com FILE * pFile; long lSize; char * buffer; size_t result; pFile = fopen ( "main.cpp" , "rb" ); if (pFile==NULL) { fputs ("File error",stderr); exit (1); } // obtain file size: fseek (pFile , 0 , SEEK_END); lSize = ftell (pFile); rewind (pFile); buffer = (char*) malloc (sizeof(char)*lSize); if (buffer == NULL) { fputs ("Memory error",stderr); exit (2); } result = fread (buffer,1,lSize,pFile); if (result != lSize) { fputs ("Reading error",stderr); exit (3); } printf("whole file is loaded in memory."); fclose (pFile); free (buffer); return 0; }