C++ file operations require the <fstream> header. Files are categorized into two types:
- Text files: Stored as ASCII text that is human-readable.
- Binary files: Stored in binary format, not directly readable by users.
Three primary classes handle file operations:
ofstream: For writing to files.ifstream: For reading from files.fstream: For both reading and writting.
Text File Operations
Writing to a Text File
Steps to write to a text file:
- Include the necessary header:
#include <fstream>
- Create an output stream object:
std::ofstream outputStream;
- Open the file with a specified mode:
outputStream.open("path/to/file.txt", std::ios::out);
- Write data to the file:
outputStream << "Data to write";
- Close the file:
outputStream.close();
Common file opening modes:
std::ios::in: Open for reading.std::ios::out: Open for writing.std::ios::ate: Start at the end of the file.std::ios::app: Append data to the file.std::ios::trunc: Delete existing content before writing.std::ios::binary: Open in binary mode.
Modes can be combined using the bitwise OR operater |, e.g., std::ios::binary | std::ios::out.
Reading from a Text File
Steps to read from a text file:
- Include headers:
#include <fstream>
#include <iostream>
#include <string>
- Create an input stream object:
std::ifstream inputStream;
- Open the file and verify success:
inputStream.open("path/to/file.txt", std::ios::in);
if (!inputStream.is_open()) {
std::cerr << "Failed to open file" << std::endl;
}
- Read data using one of several methods:
// Method 1: Using extraction operator
char buffer1[1024];
while (inputStream >> buffer1) {
std::cout << buffer1 << std::endl;
}
// Method 2: Using getline with character array
char buffer2[1024];
while (inputStream.getline(buffer2, sizeof(buffer2))) {
std::cout << buffer2 << std::endl;
}
// Method 3: Using getline with std::string
std::string line;
while (std::getline(inputStream, line)) {
std::cout << line << std::endl;
}
// Method 4: Reading character by character
char ch;
while (inputStream.get(ch)) {
std::cout << ch;
}
- Close the file:
inputStream.close();
Key points:
- Use
ifstreamorfstreamfor reading. - Check file opening with
is_open(). - Always close files with
close().
Binary File Operations
Writing to a Binary File
Binary mode is specified with std::ios::binary. Use the write() member functon:
#include <fstream>
#include <iostream>
struct Employee {
char employeeName[30];
int employeeId;
};
int main() {
std::ofstream binOut("employee.dat", std::ios::out | std::ios::binary);
Employee emp = {"Alice", 101};
binOut.write(reinterpret_cast<const char*>(&emp), sizeof(emp));
binOut.close();
return 0;
}
Reading from a Binary File
Use the read() member function for binary input:
#include <fstream>
#include <iostream>
struct Employee {
char employeeName[30];
int employeeId;
};
int main() {
std::ifstream binIn("employee.dat", std::ios::in | std::ios::binary);
if (!binIn.is_open()) {
std::cerr << "Cannot open file" << std::endl;
return 1;
}
Employee emp;
binIn.read(reinterpret_cast<char*>(&emp), sizeof(emp));
std::cout << "Name: " << emp.employeeName << ", ID: " << emp.employeeId << std::endl;
binIn.close();
return 0;
}