在C++中,使用fstream库中的ifstream、ofstream和fstream类进行文件读写操作,需包含头文件;2. ifstream用于读取文件,ofstream用于写入文件,fstream支持同时读写;3. 可通过构造函数或open()方法打开文件,并用is_open()检查状态;4. 写入文件时默认覆盖原内容,读取时可使用>>操作符按格式提取数据,但遇空格会中断。

在C++中,读取和写入文本文件最常用的方式是使用标准库中的fstream。它提供了三个主要的类:ifstream(输入文件流)、ofstream(输出文件流)和fstream(输入输出文件流),分别用于读取、写入以及同时读写文件。下面详细介绍如何使用这些类进行常见的文件操作。
要使用文件流,必须包含<fstream></fstream>头文件。同时,<iostream></iostream>和<string></string>也常被用到:
#include <fstream> #include <iostream> #include <string>
关键类说明:
istream
ostream
iostream
可以使用构造函数或open()方法打开文件。建议每次打开后检查是否成功。
立即学习“C++免费学习笔记(深入)”;
std::ifstream file("example.txt");
if (!file.is_open()) {
std::cerr << "无法打开文件!" << std::endl;
return -1;
}
关闭文件使用close():
file.close();
使用std::getline()可以按行读取内容,适用于处理每行为一条记录的文本文件。
std::ifstream file("data.txt");
std::string line;
while (std::getline(file, line)) {
std::cout << line << std::endl;
}
这种方法能正确读取包含空格的整行内容,不会被空格截断。
如果文件内容以空格分隔,可以直接使用操作符提取数据:
std::ifstream file("input.txt");
int a;
double b;
std::string name;
file >> a >> b >> name;
这种方式适合格式固定的配置文件或数据表,但遇到空格会中断读取。
使用ofstream可轻松写入文件,默认会覆盖原内容:
std::ofstream outFile("output.txt");
outFile << "Hello, World!" << std::endl;
outFile << 123 << " " << 45.6 << std::endl;
outFile.close();
若想追加内容而不是覆盖,打开时指定模式:
std::ofstream outFile("output.txt", std::ios::app);
open()函数第二个参数可指定打开方式:
std::ios::in:只读(默认 ifstream)std::ios::out:只写(默认 ofstream)std::ios::app:追加写入std::ios::ate:打开后定位到末尾std::ios::trunc:打开时清空文件(默认行为)多个模式可用|组合:
file.open("log.txt", std::ios::out | std::ios::app);
假设有一个students.txt文件,每行包含姓名和成绩:
ZhangSan 89.5 LiSi 92.0 WangWu 78.5
读取并显示平均分的代码:
#include <fstream>
#include <iostream>
#include <string>
int main() {
std::ifstream file("students.txt");
std::string name;
double score, total = 0;
int count = 0;
while (file >> name >> score) {
total += score;
++count;
std::cout << name << ": " << score << std::endl;
}
if (count > 0) {
std::cout << "平均分: " << total / count << std::endl;
}
file.close();
return 0;
}
基本上就这些。掌握fstream后,处理配置文件、日志、数据导入导出等任务都会变得简单。注意及时关闭文件、检查打开状态,避免运行时错误。不复杂但容易忽略的是路径问题——确保程序运行目录下存在目标文件,或使用绝对路径。
以上就是C++如何读取文件_C++使用fstream进行文本文件读写操作详解的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号