读取写入二进制文件

读取写入二进制文件

Posted by BY on August 26, 2022

1. 读取

#include <iostream>
#include <fstream>
using namespace std;
class CStudent
{
public:
    char szName[20];
    int age;
};
int main()
{
    CStudent s;
    ifstream inFile("students.dat", ios::in | ios::binary); //二进制读方式打开
    if (!inFile)
    {
        cout << "error" << endl;
        return 0;
    }
    while (inFile.read((char *)&s, sizeof(s)))
    { //一直读到文件结束
        cout << s.szName << " " << s.age << endl;
    }
    inFile.close();
    return 0;
}

2. 写入

#include <iostream>
#include <fstream>
using namespace std;

class CStudent
{
public:
    char szName[20];
    int age;
};
int main()
{
    CStudent s;
    ofstream outFile("students.dat", ios::out | ios::binary);
    while (cin >> s.szName >> s.age)
        outFile.write((char *)&s, sizeof(s));
    outFile.close();
    return 0;
}