Reads binary data from a stream.
#include <stdio.h> size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
ptr
A pointer to the array in which the data will be stored.
size
The size of an array element, in characters.
nmemb
The maximum number of elements to read.
stream
A pointer to a file stream.
The fread() function reads a block of binary or text data and updates the file position indicator. The data read from stream are stored in the array pointed to by ptr. The size and nmemb arguments describe the size of each item and the number of items to read, respectively.
The fread() function reads nmemb items unless it reaches the end-of-file or a read error occurs.
If the file is opened in update mode (+) a file cannot be read from and then written to without repositioning the file using one of the file positioning functions ( fseek(), fsetpos(), or rewind()) unless the last read or write reached the end-of-file.
This facility may not be available on configurations of the EWL that run on platforms without file systems. fread() returns the number of items read successfully.
#include <stdio.h> #include <stdlib.h> // define the item size in bytes #define BUFSIZE 40 int main(void) { FILE *f; static char s[BUFSIZE] = "The quick brown fox"; char target[BUFSIZE]; // create a new file for output and input if (( f = fopen("foo", "w+")) == NULL) { printf("Can't create file.\n"); exit(1); } // output to the stream using fwrite() fwrite(s, sizeof(char), BUFSIZE, f); // move to the beginning of the file rewind(f); // now read from the stream using fread() fread(target, sizeof(char), BUFSIZE, f); // output the results to the console puts(s); puts(target); // close the file fclose(f); return 0; } Output: The quick brown fox The quick brown fox