C++文件读写依赖fstream头文件中的ifstream、ofstream和fstream类,通过open()或构造函数打开文件,支持文本和二进制模式,结合ios::in、ios::out等标志控制操作方式,使用>>、<<或read()/write()进行数据读写,并通过good()、fail()等方法检查状态确保操作安全。

在C++中进行文件读写操作主要依赖于标准库中的fstream头文件,它提供了三个核心类:ifstream(用于文件输入)、ofstream(用于文件输出)和fstream(支持读写)。这些类基于C++的IO流机制,使用方式与cin和cout类似,但目标是磁盘文件。
要使用文件流,必须包含<fstream>头文件。创建对象时可直接传入文件名,或后续调用open()方法。
示例:
#include <fstream>
#include <iostream>
using namespace std;
<p>int main() {
ofstream outFile("data.txt"); // 创建输出文件流
if (outFile.is_open()) {
outFile << "Hello, C++ File!" << endl;
outFile << 123 << " " << 3.14 << endl;
outFile.close();
}</p><pre class='brush:php;toolbar:false;'>ifstream inFile("data.txt"); // 创建输入文件流
string line;
if (inFile.is_open()) {
while (getline(inFile, line)) {
cout << line << endl;
}
inFile.close();
}
return 0;}
立即学习“C++免费学习笔记(深入)”;
文件可以通过不同模式打开,控制读、写、追加、二进制等行为。模式以枚举值形式传递给构造函数或open()函数。
多个模式可用|组合。例如:
fstream file("log.txt", ios::out | ios::app); // 追加写入
fstream binFile("data.bin", ios::out | ios::binary); // 二进制写
文本模式适合字符串和基本类型,自动处理格式转换;二进制模式用于精确保存数据结构,如类对象或数组。
二进制写入示例:
struct Person {
char name[20];
int age;
};
<p>Person p = {"Tom", 25};
ofstream binOut("person.dat", ios::binary);
binOut.write(reinterpret_cast<char*>(&p), sizeof(p));
binOut.close();</p>对应读取:
ifstream binIn("person.dat", ios::binary);
Person p2;
if (binIn.read(reinterpret_cast<char*>(&p2), sizeof(p2))) {
cout << "Name: " << p2.name << ", Age: " << p2.age << endl;
}
binIn.close();
文件操作可能失败,需检查状态标志:
建议每次操作后验证状态:
ifstream file("missing.txt");
if (!file) {
cerr << "无法打开文件!" << endl;
return -1;
}
基本上就这些。掌握fstream的使用,结合模式选择和状态判断,就能高效完成C++中的文件读写任务。
以上就是C++怎么进行文件读写操作_C++ IO流编程与fstream使用指南的详细内容,更多请关注php中文网其它相关文章!
编程怎么学习?编程怎么入门?编程在哪学?编程怎么学才快?不用担心,这里为大家提供了编程速学教程(入门课程),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号