C++二进制文件读写

要求:

  •   用fstream类创建并打开二进制文件
  •   在文件中存入int,double 5 个基本数据类型
  •   自定义类,并在文件中存入一个类对象
  •   从文件中读取所有基本数据类型
  •   从文件中读取第3个基本类型数据
  •        从文件中读取类对象并使用
 1 #include<iomanip>
 2 #include <fstream>
 3 #include<iostream>
 4 #include<cstring>
 5 using namespace std;
 6 class Time {
 7 public:
 8     int year;
 9     int month;
10     void Display()
11     {
12         cout<<year<<" "<<month;
13     }
14 };
15 int main()
16 {
17     //用fstream创建并打开文件
18     fstream OutFile("binaryy.dat", ios::out| ios::in| ios::binary);
19     //写入基本数据类型
20     int a;float b;double c;char d;bool e;
21         a=1; b=1.34; c=1.3415826; d='p'; e=0;
22         OutFile.write((char *)&a,sizeof(a));
23         OutFile.write((char *)&b,sizeof(b));
24         OutFile.write((char *)&c,sizeof(c));
25         OutFile.write((char *)&d,sizeof(d));
26         OutFile.write((char *)&e,sizeof(e));
27     //写入类对象
28         Time t;
29         cin>>t.year>>t.month;
30         OutFile.write((char *) &t, sizeof(t));
31     OutFile.close();
32     fstream inFile("binaryy.dat", ios::in | ios::binary);
33     if (!inFile)
34     {
35         cout << "error" << endl;
36         return 0;
37     }
38     //int a;float b;double c;char d;bool e;
39     //读取所有基本类型
40     inFile.read((char *)&a,sizeof(a));
41         //cout<<a<<endl;
42     inFile.read((char *)&b,sizeof(b));
43         //cout<<b<<endl;
44     inFile.read((char *)&c,sizeof(c));
45         //cout<<c<<endl;
46     inFile.read((char *)&d,sizeof(d));
47         //cout<<d<<endl;
48     inFile.read((char *)&e,sizeof(e));
49         //cout<<e<<endl;
50     cout<<a<<" "<<b<<" "<<c<<" "<<d<<" "<<e<<endl;
51     //读取类对象
52     inFile.read((char *)&t,sizeof(t));
53         cout << t.year << " " << t.month << endl;
54     //读取第三个基本类型
55     double tmp;
56     inFile.seekg(sizeof(int)+sizeof(float),ios::beg);
57     //while(inFile.get(tmp))    cout<<tmp;
58     inFile.read((char *)&tmp,sizeof(double));
59     cout<<tmp<<endl;
60     //使用类对象
61     t.Display();
62     inFile.close();
63     return 0;
64 }

结果如下:

  

猜你喜欢

转载自www.cnblogs.com/DSYR/p/9157461.html