Syntax
#include <stdio.h> size_t fread(void *buffer, size_t size, size_t count, FILE *stream);Description
fread reads up to count items of size length from the input stream and stores them in the given buffer. The position in the file increases by the number of bytes read.
fread returns the number of full items successfully read, which can be less than count if an error occurs or if the end-of-file is met before reaching count. If size or count is 0, fread returns zero and the contents of the array and the state of the stream remain unchanged.
Use ferror and feof to distinguish between a read error and an end-of-file.
This example attempts to read NUM_ALPHA characters from the file myfile.dat. If there are any errors with either fread or fopen, 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]; if ((stream = fopen("myfile.dat", "r")) != NULL) { num = fread(buffer, sizeof(char), NUM_ALPHA, stream); if (num) { /* fread success */ printf("Number of characters has been read = %i\n", num); buffer[num] = '\0'; printf("buffer = %s\n", buffer); fclose(stream); } else { /* fread failed */ if (ferror(stream)) /* possibility 1 */ perror("Error reading myfile.dat"); else if (feof(stream)) /* possibility 2 */ perror("EOF found"); } } else perror("Error opening myfile.dat"); return 0; /**************************************************************************** The output should be: Number of characters has been read = 26 buffer = abcdefghijklmnopqrstuvwxyz ****************************************************************************/ }Related Information