Index
File
To use the fstream
library in C++, you need to include both the standard <iostream>
and the <fstream>
header files. Here’s how you include them:
#include <iostream>
#include <fstream>
There are three classes included in the fstream
library, which are used to create, write or read files:
Class | Description |
---|---|
ofstream | Creates and writes to files |
ifstream | Reads from files |
fstream | A combination of ofstream and ifstream: creates, reads, and writes to files |
Create and write to a file
To create a file in C++ using either the ofstream
or fstream
class and to write to the file using the insertion operator (<<
), you can follow these steps:
- Include the necessary header file:
<fstream>
for file stream operations. - Create an object of the
ofstream
orfstream
class, specifying the name of the file you want to create. - Use the insertion operator (
<<
) to write data to the file.
Example:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// Create and open a text file
ofstream MyFile("filename.txt");
// Write to the file
MyFile << "File is empty";
// Close the file
MyFile.close();
}
Read a file
To read from a file in C++ using either the ifstream
or fstream
class, and to read the file line by line using the getline()
function within a while loop, you can follow these steps:
- Include the necessary header file:
<fstream>
for file stream operations. - Create an object of the
ifstream
orfstream
class, specifying the name of the file you want to read from. - Use the
getline()
function within a while loop to read the file line by line. - Process the content of each line as needed.
Example:
#include <iostream>
#include <fstream> // For file stream operations
int main() {
// Create an object of ifstream or fstream class and specify the name of the file
std::ifstream inputFile("input.txt"); // This will open a file named "input.txt" for reading
// Check if the file is opened successfully
if (inputFile.is_open()) {
std::string line;
// Read the file line by line using getline() function
while (std::getline(inputFile, line)) {
// Process each line as needed
std::cout << line << std::endl; // Print the content of the line
}
// Close the file
inputFile.close();
} else {
// Display an error message if the file cannot be opened
std::cerr << "Unable to open file for reading." << std::endl;
return 1; // Return an error code
}
return 0; // Return 0 to indicate successful execution
}
Output:
Unable to open file for reading.