c++文件与二进制文件

//#include <iostream>
//using namespace std;
//#include <fstream>//头文件(读或写)
//#include <string.h>
//
写文件
//void test01() {
//    ofstream ofs;//创建流对象
//    ofs.open("test.txt", ios::out);//指定打开方式。ios::out是只写进入,ios::in是只读
//    ofs << "姓名:张三" << endl;
//    ofs << "职业:学生" << endl;
//    ofs << "姓名:张宇超" << endl;
//    ofs.close();
//}
//
读文件
//void test02() {
//    ifstream ifs;
//    ifs.open("test.txt", ios::in);
//    if (!ifs.is_open()) {//bool类型看能不能打开
//        cout << "文件打开失败" << endl;
//        return;
//    }
//    //读文件
//    char buf[1024] = { 0 };
//    while (ifs >> buf) {//ifs读取,储存到buf中
//        cout << buf << endl;
//    }
//
//    //    string buf;
//    //while (getline(ifs,buf)) {
//    //cout << buf << endl;
//    //}
//    ifs.close();
//    }
//    int main() {
//        test01();
//        test02();
//
//    }
    //二进制文件读与写
#include <iostream>
using namespace std;
#include <fstream>//头文件(读或写)
#include <string.h>
class person {
public:
    char m_name[64];
    int m_age;
};
person p = { "张三",18 };
void test01(){
    //包含头文件,
    //创建流对象,
    ofstream ofs;
    // 打开文件,
ofs.open("person.txt", ios::out| ios::binary);
    // 写文件

ofs.write((const char*)&p, sizeof(person));//穿地址
//关闭文件
ofs.close();
}
//读文件
void test02() {
    ifstream ifs;
    ifs.open("person.txt", ios::in |ios:: binary);
        if (!ifs.is_open()) {//bool类型看能不能打开
        cout << "文件打开失败" << endl;
        return;
    }
        ifs.read((char*)&p, sizeof(person));
        cout << "姓名是" << p.m_name << "年龄是" << p.m_age << endl;
        ifs.close();
}
int main() {
    test01();
    test02();

}

  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值