size_t fread(void * buffer, size_t size, size_t count, FILE * stream)
buffer
: This is the pointer to the buffer where data will be stored. A buffer is a region of memory used to store data temporarily.size
: This is the size (in bytes) of each character to be read.count
: This is the total number of characters (each with a size size
) to be read from the file.stream
: This is the pointer to the FILE object from where the data is to be read.A single-line string can be read from a file as follows:
#include<stdio.h>int main() {char buffer[20]; // Buffer to store dataFILE * stream;stream = fopen("file.txt", "r");int count = fread(&buffer, sizeof(char), 20, stream);fclose(stream);// Printing data to check validityprintf("Data read from file: %s \n", buffer);printf("Total number of elements read: %d", count);return 0;}
We pass the argument to the size
parameter is sizeof(char)
. This means that the size (in bytes) of each element to be read from the file is the same as the size of a single char
, which is
Using fread()
to read data into an int
variable isn't as simple, and this is demonstrated by the example below:
1234
It can be seen above that even though file.txt
contained the sequence of characters 1234
, reading it from the file into an int
leads to an unexpected output of 875770417
. This is because when reading data from a file, the fread()
function assumes that it is in a binary format (the fread()
function reads a byte stream in binary format), whereas our file was written in a text format. This function works fine when reading file content into a char
(or char
array) though, because characters are stored and read as their ASCII value.
When we need to read integers from a text file, we can use the fgets()
or fscanf()
functions instead.
If we wish to read data from a file that contains multiple rows of data, we can proceed as follows:
#include<stdio.h>int main() {char buffer[50]; // Buffer to store dataFILE * stream;stream = fopen("file.txt", "r");int count = fread(&buffer, sizeof(char), 30, stream);fclose(stream);// Printing data to check validityprintf("Data read from file: \n\%s \n", buffer);printf("Elements read: %d", count);return 0;}
The fread()
function treats the \n
character as a single character too, and thus a total of 27 characters are read.
Free Resources