64,647
社区成员
发帖
与我相关
我的任务
分享
#include <string>
#include <fstream>
#include <iostream>
using namespace std;
typedef struct {
int x;
int y;
} point_t;
/* test.dat 0x10 等于16, 写入16字节长度字符串, 再接着写入一个8字节的结构体
00000000h: 10 00 00 00 59 6F 75 20 61 72 65 20 77 65 6C 63 ; ....You are welc
00000010h: 6F 6D 65 21 50 00 00 00 33 00 00 00 ; ome!P...3...
*/
int main(int argc, char* argv[])
{
/* 二进制文件的写入 */
ofstream ofs("test.dat", ios::binary);
/* 写入字符串 */
string a = "You are welcome!";
int n = a.size();
ofs.write((char*)&n, sizeof(int));
ofs.write(a.c_str(), sizeof(char) * n);
/* 写入结构体 */
point_t b = {80, 51};
ofs.write((char*)&b, sizeof(point_t));
ofs.close();
/* 二进制文件读取 */
ifstream ifs("test.dat", std::ios::binary);
/* 读取字符串 */
int m;
ifs.read((char*)&m, sizeof(int));
char* c = new char[m + 1];
ifs.read(c, sizeof(char) * m);
c[m] = '\0';
/* 读取结构体 */
point_t d;
ifs.read((char*)&d, sizeof(point_t));
ifs.close();
/* 显示读取数据 */
cout << c << endl;
cout << '(' << d.x << ',' << d.y << ')' << endl;
return 0;
}
代码不错
#include <string>
#include <fstream>
#include <iostream>
using namespace std;
typedef struct
{
int x;
int y;
}point_t;
int main(int argc, char* argv[])
{
/* 二进制文件的写入 */
ofstream ofs("test.dat", ios::binary);
/* 写入字符串 */
string a = "You are welcome!";
int n = a.size();
ofs.write((char*)&n, sizeof(int));
ofs.write(a.c_str(), sizeof(char) * n);
/* 写入结构体 */
point_t b = {80, 51};
ofs.write((char*)&b, sizeof(point_t));
ofs.close();
/* 二进制文件读取 */
ifstream ifs("test.dat", std::ios::binary);
/* 读取字符串 */
int m;
ifs.read((char*)&m, sizeof(int));
char* c = new char[m + 1];
ifs.read(c, sizeof(char) * m);
c[m] = '\0';
/* 读取结构体 */
point_t d;
ifs.read((char*)&d, sizeof(point_t));
ifs.close();
/* 显示读取数据 */
cout << c << endl;
cout << '(' << d.x << ',' << d.y << ')' << endl;
return 0;
}