#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;
}