c++二进制文件的读写

#include "stdafx.h"

#include "string"
#include <fstream>

using namespace std;

class C
{
public:
    C():i(),str(){};//初始化,非赋值
    C(int iP,string strP):i(iP),str(strP){};
private:
    int i;
    string str;
};

void main()
{
    char *filePath = "D:/123.data";

    ofstream fout;
    fout.open(filePath,ofstream::binary);
    int n = 100;
    fout.write((char *)&n,sizeof(n));//读写都要做这样的转换(char *)&n
    C cOut(1,"ok");
    fout.write((char *)&cOut,sizeof(C));
    fout.close();

    ifstream fin;
    fin.open(filePath,ifstream::binary);
    int m = 0;
    fin.read((char *)&m,sizeof(int));
    C cIn;
    fin.read((char *)&cIn,sizeof(C));
    fin.close();
}
原文地址:https://www.cnblogs.com/rednodel/p/5123405.html