C++基础——文件操作

1 概述

程序最基本的操作之一就是文件操作,程序运行时的数据都是临时数据,当程序结束后就不复存在了。通常都是通过文件或其他持久化存储方式存储程序运算完成的数据。
文件类型可分为:

  • 文本文件:文本文件以ascii码存储到计算机中
  • 二进制文件:文件以二进制方式存储在计算机中,难以阅读

操作文件相关的类:

  • ofstream:写操作
  • ifstream:读操作
  • fstream:读写操作

2 文本文件

2.1 写文件

2.1.1 写文件流程

#include <iostream>
#include <fstream>

using namespace std;

int main() {
    ofstream out;
    out.open("./test.txt", ios::out);
    out << "hello world";
    out.close();
    return 0;
}

在这里插入图片描述

如果文件不存在,则会创建一个文件,并写入数据

2.1.2 文件打开方式

对于文件的读写,都需要先打开文件

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

这些方式可以配合使用,采用或运算符。
比如二进制写入 ios::binary | ios::out

2.2 读文件

#include <iostream>
#include <fstream>

using namespace std;

int main() {
    ifstream in;
    in.open("./test.txt", ios::in);
    if (!in.is_open()) {
        cout << "open file failed" << endl;
        return 0;
    }

    char buff1[1024] = {0};
    while (in >> buff1) {
        cout << buff1 << endl;
    }

    in.clear();
    in.seekg(0, ios::beg);
    char buff2[1024] = {0};
    while(in.getline(buff2, sizeof(buff2))) {
        cout << buff2 << endl;
    }

    in.clear();
    in.seekg(0, ios::beg);
    string buff3;
    while (getline(in, buff3)) {
        cout << buff3 << endl;
    }

    in.clear();
    in.seekg(0, ios::beg);
    char c;
    while ((c = in.get()) != EOF) {
        cout << c;
    }

    in.close();

    return 0;
}

输出

hello
world
hello world
hello world
hello world

读文件操作与写文件操作类似,不过读文件有多种读取方式。
第1种读取到换行、空格等都会结束,所以是两行
后面的三种都能够输出整行。

3 二进制文件

二进制文件存储的是字符编码之后的二进制,可以通过二进制的方式打开文件,进行二进制的读写

3.1 写文件

#include <iostream>
#include <fstream>

using namespace std;

class Person {
public:
    char m_Name[64];
    int m_Age;
};

int main() {
    ofstream out("./test2", ios::out | ios::binary);
    Person p = {"zhangsan", 23};
    out.write((const char *) &p, sizeof(p));
    out.close();
}

也是通过输出流,输出为二进制模式,通过write函数调用来谢二进制数据到文件中
打开文件普通编辑器查看只是一个有很多乱码的文件,使用二进制查看则是16进制表示的二进制数据。

3.2 读文件

#include <iostream>
#include <fstream>

using namespace std;

class Person {
public:
    char m_Name[64];
    int m_Age;
};

int main() {
    ifstream in("./test2", ios::in | ios::binary);
    if (!in.is_open()) {
        cout << "test2 open fail" << endl;
        return -1;
    }
    Person p;
    in.read((char *) &p, sizeof(p));
    cout << "p.m_Name = " << p.m_Name << endl;
    cout << "p.m_Age = " << p.m_Age << endl;
}

读文件使用输入流。通过read函数调用,从文件中读取数据,可以使用对象进行读取,需要写入时按照同样的方式写入。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值