Borland C++ reference

fread

checked against scan

Reads data from a stream.

Defined in header <stdio.h>

Syntax

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

Portability

DOSUNIXWindowsANSI CC++ only
■■■■

Remarks

fread reads n items of data, each of length size bytes, from the given input stream into a block pointed to by ptr.

The total number of bytes read is (n × size).

Return value

On successful completion, fread returns the number of items (not bytes) actually read. It returns a short count (possibly 0) on end-of-file or error.

See also

Example

#include <string.h>
#include <stdio.h>

int main(void)
{
   FILE *stream;
   char msg[] = "this is a test";
   char buf[20];
   if ((stream = fopen("DUMMY.FIL", "w+")) == NULL) {
      fprintf(stderr, "Cannot open output file.\n");
      return 1;
   }
   /* write some data to the file */
   fwrite(msg, strlen(msg)+1, 1, stream);

   /* seek to the beginning of the file */
   fseek(stream, SEEK_SET, 0);

   /* read the data and display it */
   fread(buf, strlen(msg)+1, 1, stream);
   printf("%s\n", buf);
   fclose(stream);
   return 0;
}

Differences from modern implementations

Draft from general knowledge; not yet confirmed against the Borland run-time code.

  • size_t is 16 bits (unsigned int), so size and n are each at most 65535. In the small data models (tiny, small, medium) ptr is a near pointer and a single read cannot span more than one 64 KB segment.
  • Text mode translation: on a text-mode stream CR LF pairs are read as a single \n, so the number of bytes consumed from the file can exceed n × size.
  • The manual’s example passes fseek’s arguments in the wrong order: fseek(stream, SEEK_SET, 0) should be fseek(stream, 0, SEEK_SET). It only works because SEEK_SET is 0.

Modern references