8.3) ifstream in C++
ifstream stands for “input file stream” in C++, and it is a class provided by the C++ Standard Library that allows you to read data from files. It is a part of the <fstream>
header. ifstream provides a convenient and organized way to read data from files in various formats, such as text and binary.
Here’s an in-depth explanation of how to use ifstream in C++:
Table of Contents
Creating an ifstream Object
To read data from a file using ifstream, you need to create an ifstream object. The constructor of ifstream takes the file name as its parameter. You can then use this object to perform various read operations on the file.
#include <iostream>
#include <fstream>
int main() {
std::ifstream inputFile("input.txt"); // Open the file for reading
if (inputFile.is_open()) {
// Read operations here
inputFile.close(); // Close the file
} else {
std::cerr << "Failed to open the file for reading." << std::endl;
}
return 0;
}
Reading Data Using ifstream
ifstream provides various methods to read data from the file:
- Reading Lines:
The getline() function reads a line of text from the file and stores it in a string.
#include <iostream>
#include <fstream>
int main() {
std::ifstream inputFile("input.txt");
if (inputFile.is_open()) {
std::string line;
while (getline(inputFile, line)) {
std::cout << line << std::endl; // Process each line
}
inputFile.close();
} else {
std::cerr << "Failed to open the file for reading." << std::endl;
}
return 0;
}
- Reading Formatted Data:
You can use the same input operations (>>
) that you use forcin
to read formatted data from the file.
#include <iostream>
#include <fstream>
int main() {
std::ifstream inputFile("data.txt");
if (inputFile.is_open()) {
int num;
while (inputFile >> num) {
std::cout << "Read: " << num << std::endl;
}
inputFile.close();
} else {
std::cerr << "Failed to open the file for reading." << std::endl;
}
return 0;
}
- Using eof() for Loop Control:
You can use the eof() function to control loops that read from a file.
#include <iostream>
#include <fstream>
int main() {
std::ifstream inputFile("data.txt");
if (inputFile.is_open()) {
int num;
while (!inputFile.eof()) {
inputFile >> num;
if (!inputFile.eof()) {
std::cout << "Read: " << num << std::endl;
}
}
inputFile.close();
} else {
std::cerr << "Failed to open the file for reading." << std::endl;
}
return 0;
}
Error Handling
Always check whether the file has been successfully opened before performing read operations. Use the is_open()
function to verify the status of the file stream. If the file cannot be opened, you should handle the error accordingly.
ifstream
is a powerful tool for reading data from files, whether they are text files, binary files, or any other format. It provides a flexible and efficient way to process file data in your C++ programs.