Introduction
File operations are a vital part of programming, and C++ provides a robust set of functions to handle these tasks. One such function is fread(), a powerful tool used for reading data from files. This function is actually a part of the C library, but it can be used in C++ as well.
Let's delve deeper into understanding this function.
Understanding the fread() Function
fread() is a built-in function in the C library that reads data from a file and stores it in an array or a structure. The function reads binary data directly, which makes it much faster and more efficient than other file-reading functions that read data as text.
Syntax of fread()
The syntax of fread() is as follows:
size_t fread (void * ptr, size_t size, size_t count, FILE * stream);
Here's what the parameters mean:
-
ptr: This is a pointer to the block of memory where the read data will be stored.
-
size: This is the size (in bytes) of each element to be read.
-
count: This is the number of elements to be read.
- stream: This is a pointer to the file from which the data will be read.
The fread() function will return the number of items successfully read from the file. If this number is less than count, it can mean either an error occurred or the end of file (EOF) was reached.
Using fread()
Here's a simple program demonstrating the use of fread() in C++:
#include <iostream>
#include <cstdio>
using namespace std;
int main() {
FILE *fp = fopen("test.bin", "rb");
if (fp == NULL) {
cout << "File could not be opened!" << endl;
return 1;
}
int buffer[10];
size_t res = fread(buffer, sizeof(int), 10, fp);
if (res < 10) {
if (feof(fp))
cout << "End of file reached!" << endl;
else
cout << "An error occurred!" << endl;
}
for(int i = 0; i < res; i++) {
cout << buffer[i] << endl;
}
fclose(fp);
return 0;
}
In this program, we open a binary file named test.bin for reading. We then attempt to read 10 integers from the file into an array named buffer. If fewer than 10 integers are read, the program will check if it's because the end of the file was reached or because of an error. It then prints the integers that were read.
Also read - File Handling in CPP