In C, the fread()
function is used to read data from a file and store it in a buffer.
The general syntax of fread()
is as follows:
size_t fread(void * buffer, size_t size, size_t count, FILE * stream)
The fread()
takes in a number of parameters. Let’s look at each of them in detail:
Upon successful execution, the function returns an integer value equivalent to count. In case of an error or EOF
, a value less than count is returned.
Let’s take a look at some examples to see how the fread()
function works!
#include<stdio.h> int main() { char buffer[20]; // Buffer to store data FILE * stream; stream = fopen("file.txt", "r"); int count = fread(&buffer, sizeof(char), 20, stream); fclose(stream); // Printing data to check validity printf("Data read from file: %s \n", buffer); printf("Elements read: %d", count); return 0; }
#include<stdio.h> int main() { int buffer; int store = 1234; // Creating a file and storing an int value FILE * stream; stream = fopen("file.txt", "w"); fwrite(&store, sizeof(int), 1, stream); fclose(stream); // Reading value from file stream = fopen("file.txt", "r"); fread(&buffer, sizeof(int), 1, stream); printf("Reading high score: %d\n",buffer); fclose(stream); return(0); }
If you 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 data FILE * stream; stream = fopen("file.txt", "r"); int count = fread(&buffer, sizeof(char), 30, stream); fclose(stream); // Printing data to check validity printf("Data read from file: %s \n", buffer); printf("Elements read: %d", count); return 0; }
RELATED TAGS
View all Courses