C: Reading data from a file using fread()

Cfile handlinginputfread

In C, the fread() function is used to read data from a file and store it in a buffer.

svg viewer

Syntax

The general syntax of fread() is as follows:

size_t fread(void * buffer, size_t size, size_t count, FILE * stream)

Parameters

The fread() takes in a number of parameters. Let’s look at each of them in detail:

  • Buffer: Pointer to the buffer where data will be stored. A buffer is a region of memory used to temporarily store data
  • Size: The size of each element to be read in bytes
  • Count: Number of elements to be read
  • Stream: Pointer to the FILE object from where data is to be read

Return value

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.

Example

Let’s take a look at some examples to see how the fread() function works!

1. Reading a string from a file

main.c
file.txt
#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;
}

2. Reading an integer value from file

#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);
}

3. Reading multiple values from a file

If you wish to read data from a file that contains multiple rows of data, we can proceed as follows:

main.c
file.txt
#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;
}