File I/O in C++
Introduction to File I/O
File Input and Output (I/O) in C++ is an essential concept that allows programs to read from and write to files. This is crucial for data storage, configuration management, logging, and more. In C++, the fstream
library provides the necessary tools to perform file operations.
Including the fstream Library
To use file I/O features in C++, you need to include the fstream
library. This is done by adding the following line at the beginning of your code:
#include <fstream>
Opening a File
Files can be opened in different modes, such as read, write, and append. Here’s how you can open a file:
#include <fstream>
using namespace std;
int main() {
fstream file;
file.open("example.txt", ios::out | ios::app); // Open a file in write and append mode
if (!file) {
cout << "File not created!";
} else {
cout << "File created successfully!";
}
file.close();
return 0;
}
Writing to a File
Writing to a file is straightforward. After opening the file in write mode, you can use the insertion operator (<<
) to write data:
#include <fstream>
using namespace std;
int main() {
ofstream file("example.txt");
if (file.is_open()) {
file << "Hello, World!\n";
file << "Writing to a file in C++.\n";
file.close();
} else {
cout << "Unable to open file";
}
return 0;
}
Reading from a File
Reading from a file is done using the extraction operator (>>
) or the getline
function. Here’s an example:
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ifstream file("example.txt");
if (file.is_open()) {
string line;
while (getline(file, line)) {
cout << line << '\n';
}
file.close();
} else {
cout << "Unable to open file";
}
return 0;
}
Writing to a file in C++.
File Modes
File modes determine the operations you can perform on a file. Common file modes include:
ios::in
: Open for readingios::out
: Open for writingios::app
: Append to the end of the fileios::trunc
: Truncate the fileios::binary
: Open in binary mode
Closing a File
Always close a file after you are done using it. This is done using the close()
method:
file.close();
Example: Complete Program
Below is a complete program that demonstrates file I/O in C++:
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ofstream outFile("example.txt");
if (outFile.is_open()) {
outFile << "Hello, World!\n";
outFile << "Writing to a file in C++.\n";
outFile.close();
}
ifstream inFile("example.txt");
if (inFile.is_open()) {
string line;
while (getline(inFile, line)) {
cout << line << '\n';
}
inFile.close();
}
return 0;
}
Conclusion
File I/O in C++ is a powerful feature that allows you to interact with files for reading and writing data. By understanding how to open, read, write, and close files, you can effectively manage data storage and retrieval within your C++ programs.