使用ifstream读取文件需包含,创建对象并检查是否成功打开,可用getline逐行读取或>>操作符按单词读取,最后可自动或手动关闭文件。
在C++中,读取文件内容通常使用标准库中的fstream头文件提供的ifstream类。它用于从文件中输入(读取)数据,是处理文本文件或二进制文件的基础工具。
要使用ifstream,需要包含
#include
#include
#include
using namespace std;
创建一个ifstream对象,并传入文件路径来打开文件。建议
始终检查文件是否成功打开,避免后续操作出错。
ifstream file("example.txt");
if (!file.is_open()) {
cout << "无法打开文件!" << endl;
return -1;
}
使用getline()函数可以按行读取文本内容,适合处理日志、配置文件等。
string line;
while (getline(file, line)) {
cout << line << endl;
}
这段代码会逐行输出文件中的所有内容。
如果文件内容由空格分隔的单词组成,可以直接用>>操作符读取:
string word;
while (file >> word) {
cout << word << endl;
}
这种方式会跳过空白字符(空格、换行、制表符),适合解析结构化文本。
#include
#include
#include
using namespace std;
int main() {
ifstream file("data.txt");
if (!file) {
cout << "打开文件失败!" << endl;
return 1;
}
string line;
while (getline(file, line)) {
cout << line << endl;
}
file.close(); // 可选:析构函数会自动关闭
return 0;
}