File Input/Output (I/O) streams in C++ provide a powerful mechanism for reading from and writing to files. They are an essential part of the C++ Standard Library, offering a flexible and efficient way to handle file operations.
C++ uses three main classes for file operations:
ifstream
: For reading from files (input)ofstream
: For writing to files (output)fstream
: For both reading and writingThese classes are derived from the iostream
class, inheriting its functionality for stream operations.
To work with files, you first need to open them. Here's a basic example:
#include <fstream>
#include <iostream>
int main() {
std::ofstream outFile("example.txt");
if (outFile.is_open()) {
outFile << "Hello, File I/O!" << std::endl;
outFile.close();
} else {
std::cout << "Unable to open file" << std::endl;
}
return 0;
}
In this example, we open a file for writing, check if it's open, write some text, and then close it. Always remember to close files after you're done with them.
Reading from files is just as straightforward. Here's how you can read from a file:
#include <fstream>
#include <iostream>
#include <string>
int main() {
std::ifstream inFile("example.txt");
std::string line;
if (inFile.is_open()) {
while (getline(inFile, line)) {
std::cout << line << std::endl;
}
inFile.close();
} else {
std::cout << "Unable to open file" << std::endl;
}
return 0;
}
This code opens a file, reads it line by line, and prints each line to the console.
C++ file streams support various advanced operations:
File I/O streams in C++ provide a robust and flexible way to handle file operations. They are essential for tasks ranging from simple data storage to complex file processing. By mastering these concepts, you'll be well-equipped to handle various file-related tasks in your C++ programs.
For more advanced file handling, explore Reading from Files and Writing to Files in C++.