C++ - File Streams and Binary File Handling in C++
File handling in C++ allows programs to store data permanently in files instead of keeping it only in memory. This is useful when a program needs to save information so that it can be used again later. C++ provides file handling through the fstream library.
There are mainly three classes used for file operations:
-
ifstream – Used to read data from a file.
-
ofstream – Used to write data to a file.
-
fstream – Used for both reading and writing.
To use file streams, the header file must be included.
#include <fstream>
Text files store data in human-readable form, while binary files store data in raw binary format. Binary files are faster and more efficient for storing structured data such as objects.
Opening a file in C++ can be done using the open() function or directly while creating the object.
Example of writing to a text file:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream file("data.txt");
file << "Welcome to C++ File Handling";
file.close();
return 0;
}
Example of reading from a text file:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream file("data.txt");
string text;
while(getline(file, text)) {
cout << text << endl;
}
file.close();
return 0;
}
Binary file handling is used when storing data like structures or objects. Instead of writing text, the program writes the actual memory representation of data.
Example of writing to a binary file:
#include <iostream>
#include <fstream>
using namespace std;
struct Student {
int id;
char name[20];
};
int main() {
Student s = {1, "Rahul"};
ofstream file("student.dat", ios::binary);
file.write((char*)&s, sizeof(s));
file.close();
return 0;
}
Example of reading from a binary file:
#include <iostream>
#include <fstream>
using namespace std;
struct Student {
int id;
char name[20];
};
int main() {
Student s;
ifstream file("student.dat", ios::binary);
file.read((char*)&s, sizeof(s));
cout << s.id << " " << s.name;
file.close();
return 0;
}
Binary files are commonly used in applications such as databases, game development, and systems programming because they allow fast storage and retrieval of structured data.
In summary, file streams in C++ help programs read and write data to files, while binary file handling provides a more efficient way to store and manage complex data structures.