Header: <ifstream>
The <ifstream>
header is part of the C++ Standard Library's I/O stream classes. It provides the std::ifstream
class, which is used for reading from files. This class inherits from std::istream
and adds file-specific functionality.
std::ifstream
: The main class for file input operations#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ifstream file("example.txt");
if (file.is_open()) {
std::string line;
while (std::getline(file, line)) {
std::cout << line << std::endl;
}
file.close();
} else {
std::cerr << "Unable to open file" << std::endl;
}
return 0;
}
std::getline
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ifstream file("data.txt");
if (file.is_open()) {
int id;
std::string name;
double score;
while (file >> id >> name >> score) {
std::cout << "ID: " << id << ", Name: " << name << ", Score: " << score << std::endl;
}
file.close();
} else {
std::cerr << "Unable to open file" << std::endl;
}
return 0;
}
>>
to read different types of data#include <iostream>
#include <fstream>
#include <vector>
struct Record {
int id;
char name[20];
double score;
};
int main() {
std::ifstream file("records.bin", std::ios::binary);
if (file.is_open()) {
Record record;
std::vector<Record> records;
while (file.read(reinterpret_cast<char*>(&record), sizeof(Record))) {
records.push_back(record);
}
file.close();
for (const auto& r : records) {
std::cout << "ID: " << r.id << ", Name: " << r.name << ", Score: " << r.score << std::endl;
}
} else {
std::cerr << "Unable to open file" << std::endl;
}
return 0;
}
std::ios::binary
flag to open the file in binary modestd::fstream
for both reading and writing to the same fileThe <ifstream>
header and std::ifstream
class provide a convenient and type-safe way to read data from files in C++.
std::ifstream
for file input operationsBy using <ifstream>
, C++ developers can easily implement file reading operations, whether for simple text files or more complex binary data structures. It provides a flexible and object-oriented approach to file I/O, consistent with C++'s stream-based input/output philosophy.