C++如何使用fstream读写文件

C++中fstream用于文件读写,包含ofstream、ifstream和fstream三个类,通过open()或构造函数打开文件,支持多种模式如ios::in、ios::out、ios::app、ios::binary等,可组合使用,操作时需检查is_open()、good()、fail()、bad()、eof()等状态,文本文件用操作,二进制文件用read()和write(),最后调用close()关闭文件。

c++如何使用fstream读写文件

在C++中,使用

fstream

可以方便地进行文件的读写操作。它位于


头文件中,提供了三个主要类:

ofstream:用于写入文件(output file stream)ifstream:用于读取文件(input file stream)fstream:既可以读也可以写

打开和关闭文件

要操作文件,首先要打开它。可以通过构造函数或

open()

方法打开文件,操作完成后调用

close()

关闭。

#include
#include iostream>
using namespace std;

int main() {
    ofstream outFile(“example.txt”);
    if (!outFile) {
        cout         return 1;
    }
    outFile     outFile.close();

    ifstream inFile(“example.txt”);
    if (!inFile) {
        cout         return 1;
    }
    string line;
    while (getline(inFile, line)) {
        cout     }
    inFile.close();
    return 0;
}

读写模式说明

fstream

支持多种打开模式,通过参数指定:

ios::out – 写入,文件不存在则创建ios::in – 读取ios::app – 追加写入,每次写都在末尾ios::trunc – 写入时清空原内容(默认)ios::binary – 以二进制方式操作

多个模式可以用

|

组合:

立即学习“C++免费学习笔记(深入)”;

fstream file;
file.open(“data.txt”, ios::in | ios::out);
if (file.is_open()) {
    file     file.seekg(0); // 移动读取指针到开头
    string s;
    file >> s;
    cout     file.close();
}

检查文件状态

操作文件时应检查状态,避免出错。常用方法包括:

is_open() – 文件是否成功打开good() – 所有状态正常fail() – 操作失败(如格式错误)eof() – 是否到达文件末尾bad() – 发生严重错误(如磁盘故障)

推荐在读写后判断是否成功:

ifstream in(“test.txt”);
if (in.is_open()) {
    string data;
    if (!(in >> data)) {
        cout     }
    in.close();
} else {
    cout }

二进制文件读写

处理非文本数据时,使用

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(&p), sizeof(p));
out.close();

ifstream in(“person.dat”, ios::binary);
Person p2;
in.read(reinterpret_cast(&p2), sizeof(p2));
cout in.close();

基本上就这些。掌握好打开、读写、状态检查和关闭流程,就能安全高效地使用 fstream 操作文件。

以上就是C++如何使用fstream读写文件的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1475641.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
C++如何使用fstream实现临时文件操作
上一篇 2025年12月18日 23:33:58
C++智能指针管理动态对象生命周期解析
下一篇 2025年12月18日 23:34:12

相关推荐

发表回复

登录后才能评论
关注微信