12.2.2重学C++之【读二进制文件】

#include<stdlib.h>
#include<iostream>
#include<fstream>
using namespace std;



/*
    5.2.2 读二进制文件
        二进制方式读文件主要利用流对象调用成员函数read
        函数原型:istream & read(char * buffer, int len);
        参数解释:字符指针buffer指向内存中一段存储空间。len是读写的字节数
*/



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



void test(){
    ifstream ifs;
    ifs.open("person.txt", ios::in|ios::binary);

    if(!ifs.is_open()){
        cout << "文件打开失败" << endl;
        return;
    }

    Person p;
    ifs.read((char *)&p, sizeof(Person));
    cout << p.name << endl;
    cout << p.age << endl;

    ifs.close();
}



int main()
{
    test();

    system("pause");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/HAIFEI666/article/details/114981267
今日推荐