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

在C++中读取文件内容主要使用标准库中的fstream头文件,它提供了ifstream(输入文件流)来读取文件。以下是几种常用的文件读取方法,适用于不同场景。
适合读取文本文件,尤其是每行有独立含义的情况(如配置文件、日志等)。
使用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;
}
适用于小文件,想快速获取全部内容。
立即学习“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;
}
适合需要逐个处理字符的场景,比如统计字符数或解析特定格式。
使用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;
}
适合处理以空格分隔的数据,比如读取数字列表或单词。
#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;
}
注意事项:
以上就是c++++中如何读取文件内容_c++文件读取方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号