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;
}
相关推荐
bkspiderx11 分钟前
C++设计模式之行为型模式:状态模式(State)
c++·设计模式·状态模式
会开花的二叉树30 分钟前
分布式文件存储 RPC 服务实现
c++·分布式·网络协议·rpc
abcd_zjq1 小时前
VS2026+QT6.9+opencv图像增强(多帧平均降噪)(CLAHE对比度增强)(边缘增强)(图像超分辨率)
c++·图像处理·qt·opencv·visual studio
Algebraaaaa2 小时前
Qt中的字符串宏 | 编译期检查和运行期检查 | Qt信号与槽connect写法
开发语言·c++·qt
Predestination王瀞潞7 小时前
IO操作(Num22)
开发语言·c++
宋恩淇要努力8 小时前
C++继承
开发语言·c++
江公望10 小时前
Qt qmlRegisterSingletonType()函数浅谈
c++·qt
逆小舟12 小时前
【C/C++】指针
c语言·c++·笔记·学习
江公望12 小时前
Qt QtConcurrent使用入门浅解
c++·qt·qml
我是华为OD~HR~栗栗呀12 小时前
23届考研-Java面经(华为OD)
java·c++·python·华为od·华为·面试