C++文件操作需包含fstream头文件,使用ofstream写入、ifstream读取、fstream读写文件,支持文本和二进制模式,需检查文件是否打开并选择合适模式。

在C++中进行文件读写操作,主要使用标准库中的 fstream 头文件。它提供了三个核心类:
ifstream:用于从文件读取数据(input file stream) ofstream:用于向文件写入数据(output file stream) fstream:同时支持读写操作
下面通过具体示例详细讲解如何使用这些类完成常见的文件操作。
1. 包含头文件
#include
#include iostream>
#include
这三个头文件分别用于文件操作、输入输出和字符串处理。
2. 写入文件(ofstream)
使用 ofstream 向文件中写入内容。如果文件不存在会自动创建;如果已存在,默认会覆盖原内容。
立即学习“C++免费学习笔记(深入)”;
std::ofstream file(“example.txt”);
if (file.is_open()) {
file file file.close();
} else {
std::cout }
你也可以以追加模式写入,避免覆盖原内容:
std::ofstream file(“example.txt”, std::ios::app);
file
3. 读取文件(ifstream)
使用 ifstream 从文件读取内容。可以逐行读取或按单词读取。
std::ifstream file(“example.txt”);
std::string line;
if (file.is_open()) {
while (getline(file, line)) {
std::cout }
file.close();
} else {
std::cout }
注意:getline(file, line) 每次读取一行,直到遇到换行符为止。
4. 同时读写文件(fstream)
当你需要对同一个文件进行读写操作时,使用 fstream 类,并指定模式。
std::fstream file(“example.txt”, std::ios::in | std::ios::out);
// 先读取所有内容
std::string content;
while (getline(file, content)) {
std::cout }
// 移动指针到末尾再写入
file
常见打开模式:
std::ios::in:读取 std::ios::out:写入(默认会清空文件) std::ios::app:追加 std::ios::ate:打开后立即定位到文件末尾 std::ios::binary:二进制模式
5. 检查文件是否存在
可以通过尝试打开文件来判断是否存在:
std::ifstream file(“example.txt”);
if (!file) {
std::cout } else {
std::cout file.close();
}
6. 二进制文件读写
对于非文本文件(如图片、音频),应使用二进制模式。
// 写入二进制
std::ofstream out(“data.bin”, std::ios::binary);
int data = 12345;
out.write(reinterpret_cast(&data), sizeof(data));
out.close();
// 读取二进制
std::ifstream in(“data.bin”, std::ios::binary);
int value;
in.read(reinterpret_cast(&value), sizeof(value));
in.close();
std::cout
使用 read() 和 write() 函数处理原始字节数据。
7. 完整示例:读写学生信息
#include
#include
#include
int main() {
// 写入数据
std::ofstream out(“students.txt”);
if (out.is_open()) {
out out out.close();
}
// 读取数据
std::ifstream in(“students.txt”);
std::string name;
int age;
if (in.is_open()) {
while (in >> name >> age) {
std::cout }
in.close();
}
return 0;
}
基本上就这些。掌握这些方法后,就能处理大多数C++文件操作任务了。关键是记得检查文件是否成功打开,并根据需求选择合适的模式。不复杂但容易忽略细节。
以上就是c++++怎么读取和写入文件_c++文件读写操作完整教程的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1482614.html
微信扫一扫
支付宝扫一扫