C++——fstream文件读写操作

文件类型

  • 文本文件 - 文件以文本的ASCII码形式存储在计算机中

  • 二进制文件 - 文件以文本的二进制形式存储在计算机中,用户一般不能直接读懂它们

操作文件类

  • ofstream:写操作

  • ifstream: 读操作

  • fstream : 读写操作

文件打开方式

打开方式 解释
ios::in 为读文件而打开文件
ios::out 为写文件而打开文件
ios::ate 初始位置:文件尾
ios::app 追加方式写文件
ios::trunc 如果文件存在先删除,再创建
ios::binary 二进制方式

注意: 文件打开方式可以配合使用,利用|操作符

例如: 用二进制方式写文件 ios::binary | ios:: out

文本文件读写代码示例

cpp 复制代码
#include <ios>
#include <iostream>
#include <string>
#include <fstream>
using namespace std;

int write_file(string file_path,string file_content){
    ofstream ofs;
    ofs.open(file_path,ios::out);
    ofs<<file_content<<endl;
    ofs.close();
    return 1;
}

void read_file(string file_path){
    ifstream ifs;
    ifs.open(file_path,ios::in);
    if (!ifs.is_open()) {
        cout<<"file can't open"<<endl;
    }
    string buffer;
    while (getline(ifs,buffer)) { //get by line
        cout<<buffer<<endl;
    }
    ifs.close();
}

int main(){
    write_file("./test.txt","Hello World!\nHello Sophia!\nHello Anna!\nYumy!");
    read_file("./test.txt");
    return 1;
}

二进制文件读写代码示例

cpp 复制代码
#include <fstream>
#include <ios>
#include <iostream>
#include <string>
using namespace std;

// definded class
class Person{
public:
    char m_name[64];
    int m_age;
};

// write binary file
void write_binary_file(string file_path){
    // create ofs obj
    ofstream ofs(file_path,ios::out|ios::binary);
    //ofstream ofs;
    // open file
    //ofs.open(file_path,ios::binary);
    Person p = {"Sophia",20};
    // write
    ofs.write((const char *)&p, sizeof(p));
    // close file
    ofs.close();
}

Person p_read;
void read_binary_file(string file_path){
    // create stream aoj
    ifstream ifs(file_path,ios::in|ios::binary);
    // read
    ifs.read((char *)&p_read, sizeof(Person));
    // cout
    cout<<p_read.m_name<<"\n"<<p_read.m_age<<endl;
    // close
    ifs.close();
}

int main(){
    string file_path="./test1.txt";
    write_binary_file(file_path);
    read_binary_file(file_path);
    return 1;
}
相关推荐
hz_zhangrl9 分钟前
CCF-GESP 等级考试 2025年9月认证C++六级真题解析
c++·算法·青少年编程·程序设计·gesp·2025年9月gesp·gesp c++六级
兵哥工控36 分钟前
MFC用高精度计时器实现五段时序控制器
c++·mfc·高精度计时器·时序控制器
眠りたいです1 小时前
基于脚手架微服务的视频点播系统-服务端开发部分(补充)文件子服务问题修正
c++·微服务·云原生·架构
ULTRA??1 小时前
各种排序算法时间复杂度分析和实现和优势
c++·python·算法·排序算法
博语小屋2 小时前
简单线程池实现(单例模式)
linux·开发语言·c++·单例模式
墨雪不会编程2 小时前
C++基础语法篇八 ——【类型转换、再探构造、友元】
java·开发语言·c++
yuuki2332332 小时前
【C++】内存管理
java·c++·算法
刃神太酷啦2 小时前
Linux 进程核心原理精讲:从体系结构到实战操作(含 fork / 状态 / 优先级)----《Hello Linux!》(6)
java·linux·运维·c语言·c++·算法·leetcode
一个不知名程序员www2 小时前
算法学习入门---二叉树
c++·算法
小李小李快乐不已2 小时前
数组&&矩阵理论基础
数据结构·c++·线性代数·算法·leetcode·矩阵