C++ 二进制文件 读 写文件

 1 #include <iostream>
 2 #include <string>
 3 #include<fstream>
 4 using namespace std;
 5 
 6 class Person
 7 {
 8 public:
 9     char m_Name[64];    //姓名
10     int m_Age;          //年龄
11 };
12 
13 //写文件
14 void test01()
15 {
16     //1.包含头文件
17 
18     //2.创建流对象
19     ofstream ofs("person.txt", ios::out | ios::binary);
20     //3.打开文件
21     //ofs.open("person.txt",ios::out | ios::binary);
22 
23     //4.写文件
24     Person p = {"zhenglei",21};
25     ofs.write((const char*)&p, sizeof(Person));
26 
27     //5.关闭文件
28     ofs.close();
29 }
30 
31 
32 //二进制读文件
33 void test02()
34 {
35     //1.包含头文件
36 
37     //2.创建流对象
38     ifstream ifs;
39     //3.打开文件 判断是否打开成功
40     ifs.open("person.txt", ios::in | ios::binary);
41     if (!ifs.is_open())
42     {
43         cout << "文件打开失败!!!" << endl;
44     }
45     //4.读文件
46     Person p;
47 
48     ifs.read((char*)&p, sizeof(Person));
49     cout << "姓名:" << p.m_Name << "  年龄:" << p.m_Age << endl;
50 
51     //5.关闭文件
52     ifs.close();
53 }
54 int main()
55 {
56     test01();
57     test02();
58 
59 
60     system("pause");
61 
62     return 0;
63 
64 }

 

 

 

posted on 2021-08-09 15:20  Bytezero!  阅读(207)  评论(0编辑  收藏  举报