fread - C stdio.h

C examples for stdio.h:fread

Type

function

From


<cstdio>
<stdio.h>

Description

Read block of data from stream

Prototype

size_t fread ( void * ptr, size_t size, size_t count, FILE * stream );

Parameters

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

Return Value

The total number of elements successfully read is returned.

Example

This code loads main.cpp into memory buffer.

Demo Code


#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;
}

Related Tutorials