C++文件操作

记录C++操作文件步骤, 方便以后直接复用

一 文件操作三个类

1 ofstream: 写操作
2 ifstream: 读操作
3 fstream: 读写操作
fstream同时具有上两个类的功能,若对文件安全性无特殊需求,可以全都使用fstream操作,省心。

文件操作分两类:文件文件和二进制文件

写文件流程
包含头文件 #include <fstream>
创建流对象
写文件流对象 ofstream ofs;
读文件流对象 ifstream ifs;

打开文件 ofs.open(文件路径,打开方式);
写数据 ofs << “data”;
关闭文件 ofs.close();

文件打开方式:
在这里插入图片描述
使用二进制写文件方式:ios::out | ios::binary,其他二进制打开方式类似。

二 代码实现

txt文件读写:

#include <iostream>
// 1 包含头文件
#include <fstream>
#include <string>

using namespace std;


int main() {
    //写文件操作 =============================================
    //2 创建流对象
    ofstream ofs;
    //3 打开文件,会在当前目录自动生成文件test_write_file.txt
    ofs.open("test_file.txt", ios::out);
    //4 写数据
    ofs << "data" << endl;
    ofs << "this is a test code" << endl;
    //5 关闭文件
    ofs.close();

    //读文件操作 =============================================
    ifstream ifs;
    //打开文件,并判断是否打开成功
    ifs.open("test_file.txt", ios::in);
    if (!ifs.is_open()) {
        cout << "file open fail" << endl;
        return -1;
    }

    //读取文件数据4种方式
    //读取方式1
//    char buf1[1024] = {0};
//    while (ifs >> buf1) {
//        cout << buf1 << endl;
//    }

    //读取方式2
//    char buf2[1024] = {0};
//    while (ifs.getline(buf2, sizeof(buf2))) {
//        cout << buf2 << endl;
//    }

    //读取方式3
    string buf3;
    while (getline(ifs, buf3)) {
        cout << buf3 << endl;
    }

    //读取方式4
//    char c;
//    while ((c = ifs.get()) != EOF) { //end of file, 文件结尾标志
//        cout << c;
//    }

    //不要忘记关闭文件
    ifs.close();
    return 0;
}

以上,关于读文件,我更喜欢方式3,看个人喜好可以在方式1,2,3中选一个,不推荐方式4,效率太低。

二进制文件读写:

#include <iostream>
// 1 包含头文件
#include <fstream>
#include <string>

using namespace std;

class Teacher {
public:
    char name[64];
    int age;
};

int main() {
    //二进制写文件 =============================================
    ofstream ofs;
    Teacher t1 = {"li ming", 33};

    ofs.open("teacher.txt", ios::out | ios::binary);
//  &t1类型是Teacher,write方法需求char*类型,需要强制转换
//  函数原型:ostream& write(char *buffer, int len)
    ofs.write((const char *) &t1, sizeof(Teacher));
    ofs.close();

    //二进制读文件 =============================================
    ifstream ifs;
    ifs.open("teacher.txt", ios::in | ios::binary);
    if (!ifs.is_open()) {
        cout << "file open fail" << endl;
        return -1;
    }

    // 存储的是Teacher对象,最后也应由Teacher对象接收
    Teacher t2;
    ifs.read((char *) &t2, sizeof(Teacher));
    cout << "name = " << t2.name << endl;
    cout << "age = " << t2.age << endl;
    ifs.close();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值