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 }

結果如下:

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM