使用ifstream和getline逐行读取文本文件内容,适用于配置文件或日志等场景,需包含fstream头文件并检查文件是否成功打开。

在C++中读取文件内容主要使用标准库中的fstream头文件,它提供了ifstream(输入文件流)来读取文件。以下是几种常用的文件读取方法,适用于不同场景。
1. 逐行读取文件内容
适合读取文本文件,尤其是每行有独立含义的情况(如配置文件、日志等)。
使用std::getline()函数可以按行读取:
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ifstream file("example.txt");
std::string line;
if (!file.is_open()) {
std::cerr << "无法打开文件!" << std::endl;
return 1;
}
while (std::getline(file, line)) {
std::cout << line << std::endl;
}
file.close();
return 0;
}
2. 一次性读取整个文件到字符串
适用于小文件,想快速获取全部内容。
立即学习“C++免费学习笔记(深入)”;
可以使用std::string构造函数结合文件流迭代器实现:
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
int main() {
std::ifstream file("example.txt");
if (!file.is_open()) {
std::cerr << "无法打开文件!" << std::endl;
return 1;
}
std::stringstream buffer;
buffer << file.rdbuf(); // 读取全部内容
std::string content = buffer.str();
std::cout << content << std::endl;
file.close();
return 0;
}
3. 按字符读取
适合需要逐个处理字符的场景,比如统计字符数或解析特定格式。
使用get()函数:
#include <iostream>
#include <fstream>
int main() {
std::ifstream file("example.txt");
char ch;
if (!file.is_open()) {
std::cerr << "无法打开文件!" << std::endl;
return 1;
}
while (file.get(ch)) {
std::cout << ch;
}
file.close();
return 0;
}
4. 按单词读取(使用流操作符)
适合处理以空格分隔的数据,比如读取数字列表或单词。
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ifstream file("example.txt");
std::string word;
if (!file.is_open()) {
std::cerr << "无法打开文件!" << std::endl;
return 1;
}
while (file >> word) {
std::cout << word << std::endl;
}
file.close();
return 0;
}
注意事项:
- 每次读取前检查文件是否成功打开(is_open())。
- 读取完成后建议调用close()释放资源,虽然析构函数也会自动关闭。
- 路径支持相对路径和绝对路径,注意转义反斜杠(Windows下写成"C:\file.txt"或使用正斜杠"C:/file.txt")。
- 二进制文件读取需加上std::ios::binary标志。











