gtpc2m38C/C++ Language Support User's Guide

fread-Read Items

This function reads items.

Format

#include <stdio.h>
size_t fread(void *buffer, size_t size, size_t count, FILE *stream);

buffer
The address of the buffer into which the stream data will be read.

size
The number of bytes contained in each item to be read.

count
The number of items to be read.

stream
The stream to be read.

This function reads up to count items of size length from the input stream pointed to by stream and stores them in the given buffer. The file position indicator advances by the number of bytes read.

If there is an error during the read operation, the file position indicator is undefined. If a partial element is read, the value of the element is undefined.

The fread function has the same restriction as any read operation for a read immediately following a write, or a write immediately following a read. Between a write and a subsequent read, there must be an intervening flush or reposition. Between a read and a subsequent write, there must be an intervening reposition unless an end-of-file (EOF) has been reached.

Normal Return

The fread function returns the number of complete items successfully read. If size or count is 0, fread returns 0 and the contents of the array and the state of the stream remain unchanged.

Error Return

The ferror and feof functions are used to distinguish between a read error and an EOF. Note that EOF is only reached when an attempt is made to read beyond the last byte of data. Reading up to and including the last byte of data does not turn on the EOF indicator.

Programming Considerations

None.

Examples

The following example attempts to read NUM_ALPHA characters from the myfile.dat file. If there are any errors with either the fread or fopen functions, a message is printed.

#include <stdio.h>
#define NUM_ALPHA  26
 
int main(void)
{
  FILE * stream;
  int num;       /* number of characters read from stream */
 
  /* Do not forget that the '/0' char occupies one character too! */
  char buffer[NUM_ALPHA + 1];
  buffer[NUM_ALPHA+1] = '\0';
 
  if (( stream = fopen("myfile.dat", "r"))!= NULL )
  {
    num = fread( buffer, sizeof( char ), NUM_ALPHA, stream );
    if (num == NUM_ALPHA) {  /* fread success */
      printf( "Number of characters read = %i\n", num );
      printf( "buffer = %s\n", buffer );
      fclose( stream );
    }
    else {  /* fread() failed */
      if ( ferror(stream) )         /* possibility 1 */
        printf( "Error reading myfile.dat" );
      else if ( feof(stream)) {     /* possibility 2 */
        printf( "EOF found\n" );
        printf( "Number of characters read %d\n", num );
        printf( "buffer = %.*s\n", num, buffer);
      }
    }
  }
  else
    printf( "Error opening myfile.dat" );
}

Related Information

See Appendix E, Programming Support for the TPF File System for more information about TPF File System C Functions.