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
| DOS | UNIX | Windows | ANSI C | C++ 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_tis 16 bits (unsigned int), sosizeandnare each at most 65535. In the small data models (tiny, small, medium)ptris 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 exceedn × size. - The manual’s example passes
fseek’s arguments in the wrong order:fseek(stream, SEEK_SET, 0)should befseek(stream, 0, SEEK_SET). It only works becauseSEEK_SETis 0.
Modern references
Stable link: /3.1/stdio.h/fread/
· short form /3.1/fread/