C++ 读写二进制文件
#include <fstream>
using namespace std;
…
// AuthInfo 是自定义的 struct
struct AuthInfo auth_info;
string susername, spassword;
/* 写文件 */
// 清零
ZeroMemory ( &auth_info, sizeof ( auth_info ) );
susername = "[email protected]";
spassword = "000000";
// 内存拷贝
memcpy(auth_info.username, susername.c_str(), susername.length());
memcpy(auth_info.password, spassword.c_str(), spassword.length());
// 定义打开输出流
ofstream fout("mbc.dat", ios::binary);
// 写入
fout.write((char *)(&auth_info), sizeof(auth_info));
// 关闭输出流
fout.close();
/* 读文件 */
ZeroMemory ( &auth_info, sizeof ( auth_info ) );
ifstream fin ( "mbc.dat", ios::binary );
fin.read((char *)(&auth_info), sizeof(auth_info));
susername = auth_info.username;
spassword = auth_info.password;
ZeroMemory ( auth_info.username, 100 ); // AuthInfo.username[100]
ZeroMemory ( auth_info.password, 50 ); // AuthInfo.password[50]
memcpy(auth_info.username, susername.c_str(), susername.length());
memcpy(auth_info.password, spassword.c_str(), spassword.length());
fin.close();