C++中讀取/寫入類物件到檔案
The iostream 標準庫 具有兩個方法 cin,用於從標準輸入流接收輸入,以及 cout 用於將輸出列印到標準輸出流。在本文中,我們將學習如何將檔案中的資料讀取到類物件中,以及如何將類物件中的資料寫入檔案。
讀取和寫入檔案資料需要另一個標準庫 C++ <fstream>。fstream 的三種主要資料型別為:
- ifstream − 表示輸入檔案流,並從檔案中讀取資訊。
- ofstream − 表示輸出檔案流,並將資訊寫入檔案。
- fstream − 表示通用檔案流,並具有兩者的功能。
建立類物件
我們正在使用一個名為 Employee 的類,其 Name、Employee_ID 和 Salary 為其公有資料成員。
class Employee { public: char Name[]; long Employee_ID; int Salary; } ; Employee Emp_1; Emp_1.Name=”Jhonson”; Emp_1.Employee_ID=212020; Emp_1.Salary=11000;
建立檔案物件
語法
fstream/ofstream/ifstream object_name; void open(const char *filename, ios::openmode); ofstream file1; file1.open( “Employee.txt”, ios::app );
這裡 file1 是用於以追加模式開啟 Employee.txt 檔案的物件(新內容追加到末尾)。file1 物件的型別為 ofstream,這意味著我們可以寫入 Employee.txt。
ifstream file2; file2.open( “Employee.txt”, ios::in );
這裡 file2 是用於以輸入模式開啟 Employee.txt 檔案以讀取內容的物件。file1 物件的型別為 ifstream,這意味著我們只能從 Employee.txt 讀取資料。
寫入和讀取類物件
file1.write( (char*)&Emp_1, sizeof(Emp1) );
這裡透過呼叫 write 函式將類物件 Emp_1 中存在的資料寫入檔案 Employee.txt。(char*)&Emp_1 用於指向物件的開頭,sizeof(Emp_1) 計算寫入檔案中的位元組數。
file2.read( (char*)&Emp_1, sizeof(Emp1) );
這裡透過呼叫 read 函式將類物件 Emp_1 中存在的資料從檔案 Employee.txt 讀取。(char*)&Emp_1 用於指向物件的開頭,sizeof(Emp_1) 計算從檔案中讀取的位元組數。
關閉檔案
file1.close(); file2.close();
關閉檔案的輸入流和輸出流。
示例
#include <iostream> #include <fstream> using namespace std; // Class to define the properties class Employee { public: string Name; int Employee_ID; int Salary; }; int main(){ Employee Emp_1; Emp_1.Name="John"; Emp_1.Employee_ID=2121; Emp_1.Salary=11000; //Wriring this data to Employee.txt ofstream file1; file1.open("Employee.txt", ios::app); file1.write((char*)&Emp_1,sizeof(Emp_1)); file1.close(); //Reading data from EMployee.txt ifstream file2; file2.open("Employee.txt",ios::in); file2.seekg(0); file2.read((char*)&Emp_1,sizeof(Emp_1)); printf("\nName :%s",Emp_1.Name); printf("\nEmployee ID :%d",Emp_1.Employee_ID); printf("\nSalary :%d",Emp_1.Salary); file2.close(); return 0; }
輸出
Name: John Employee ID: 2121 Salary: 11000
廣告