cpp fread

Solutions on MaxInterview for cpp fread by the best coders in the world

showing results for - "cpp fread"
Elizabeth
25 Sep 2018
1/* fread example: read an entire file */
2#include <stdio.h>
3#include <stdlib.h>
4
5int main () {
6  FILE * pFile;
7  long lSize;
8  char * buffer;
9  size_t result;
10
11  pFile = fopen ( "myfile.bin" , "rb" );
12  if (pFile==NULL) {fputs ("File error",stderr); exit (1);}
13
14  // obtain file size:
15  fseek (pFile , 0 , SEEK_END);
16  lSize = ftell (pFile);
17  rewind (pFile);
18
19  // allocate memory to contain the whole file:
20  buffer = (char*) malloc (sizeof(char)*lSize);
21  if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}
22
23  // copy the file into the buffer:
24  result = fread (buffer,1,lSize,pFile);
25  if (result != lSize) {fputs ("Reading error",stderr); exit (3);}
26
27  /* the whole file is now loaded in the memory buffer. */
28
29  // terminate
30  fclose (pFile);
31  free (buffer);
32  return 0;
33}
Maya
30 Feb 2017
1size_t fread ( void * ptr, size_t size, size_t count, FILE * stream );