
在C++中,使用
fstream可以方便地进行文件的读写操作。它位于
<fstream>头文件中,提供了三个主要类:
- ofstream:用于写入文件(output file stream)
- ifstream:用于读取文件(input file stream)
- fstream:既可以读也可以写
要操作文件,首先要打开它。可以通过构造函数或
open()方法打开文件,操作完成后调用
close()关闭。 #include <fstream>
#include <iostream>
using namespace std;
int main() {
ofstream outFile("example.txt");
if (!outFile) {
cout << "无法打开文件用于写入!" << endl;
return 1;
}
outFile << "Hello, World!" << endl;
outFile.close();
ifstream inFile("example.txt");
if (!inFile) {
cout << "无法打开文件用于读取!" << endl;
return 1;
}
string line;
while (getline(inFile, line)) {
cout << line << endl;
}
inFile.close();
return 0;
}
fstream支持多种打开模式,通过参数指定:
- ios::out - 写入,文件不存在则创建
- ios::in - 读取
- ios::app - 追加写入,每次写都在末尾
- ios::trunc - 写入时清空原内容(默认)
- ios::binary - 以二进制方式操作
多个模式可以用
|组合: fstream file;
file.open("data.txt", ios::in | ios::out);
if (file.is_open()) {
file << "追加内容";
file.seekg(0); // 移动读取指针到开头
string s;
file >> s;
cout << s;
file.close();
} 检查文件状态
操作文件时应检查状态,避免出错。常用方法包括:
Post AI
博客文章AI生成器
50
查看详情
- is_open() - 文件是否成功打开
- good() - 所有状态正常
- fail() - 操作失败(如格式错误)
- eof() - 是否到达文件末尾
- bad() - 发生严重错误(如磁盘故障)
推荐在读写后判断是否成功:
ifstream in("test.txt");if (in.is_open()) {
string data;
if (!(in >> data)) {
cout << "读取失败!" << endl;
}
in.close();
} else {
cout << "文件打不开" << endl;
} 二进制文件读写
处理非文本数据时,使用
ios::binary模式,并配合
read()和
write()函数。 struct Person {
char name[20];
int age;
};
ofstream out("person.dat", ios::binary);
Person p = {"Tom", 25};
out.write(reinterpret_cast<char*>(&p), sizeof(p));
out.close();
ifstream in("person.dat", ios::binary);
Person p2;
in.read(reinterpret_cast<char*>(&p2), sizeof(p2));
cout << p2.name << ", " << p2.age << endl;
in.close();
基本上就这些。掌握好打开、读写、状态检查和关闭流程,就能安全高效地使用 fstream 操作文件。
以上就是C++如何使用fstream读写文件的详细内容,更多请关注知识资源分享宝库其它相关文章!
相关标签: go app ai c++ ios EOF String if while 构造函数 include char int 指针 ofstream ifstream fstream using Struct Namespace input ios 大家都在看: Golang的包管理机制如何运作 介绍go mod的依赖管理方式 C++和Go之间有哪些区别? C++文件写入模式 ios out ios app区别 C++文件流中ios::app和ios::trunc打开模式有什么区别 C++文件写入模式解析 ios out ios app区别






发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。