C++檔案輸入輸出流+輸入輸出二進位制檔案(自定義物件)
檔案流類和檔案流物件
檔案流是以外存檔案為輸入輸出物件的資料流。
輸出檔案流 記憶體->外存
輸入檔案流 外存->記憶體
檔案流類
流的名稱 | 流的作用 |
ifstream類 | 從istream類派生的,用來支援從磁碟檔案的輸入 |
ofstream類 | 從ostream類派生的,用來支援向磁碟檔案的輸出 |
fstream類 | 從iostream類派生的,用來支援對磁碟檔案的輸入輸出 |
操作:
開啟檔案:
1、呼叫檔案流的成員函式open。如
ofstream outfile;
outfile.open("f1.dat",ios::out);
2、在定義檔案流物件時指定引數在宣告檔案流類時定義了帶引數的建構函式,其中包含了開啟磁碟檔案的功能。
ostream outfile("f1.dat",ios::out);
輸入輸出格式:
ios::in | 以輸入方式開啟檔案 |
ios::out | 以輸出方式開啟檔案(這是預設方式),如果已有此名字的檔案,則將其原有內容全部清除 |
ios::app | 以輸出方式開啟檔案,寫入的資料新增在檔案末尾 |
ios::ate | 開啟一個已有的檔案,檔案指標指向檔案末尾 |
ios: :trunc | 開啟一個檔案,如果檔案已存在,則刪除其中全部資料,如檔案不存在,則建立新檔案。如已指定了 ios::out 方式,而未指定ios: :app,ios::ate,ios: :in,則同時預設此方式 |
ios:: binary | 以二進位制方式開啟一個檔案,如不指定此方式則預設為ASCII方式 |
ios::nocreate | 開啟一個已有的檔案,如檔案不存在,則開啟失敗。nocrcate的意思是不建立新檔案 |
ios:: noreplace | 如果檔案不存在則建立新檔案,如果檔案已存在則操作失敗,replace 的意思是不更新原有檔案 |
ios::in l ios::out | 以輸入和輸出方式開啟檔案,檔案可讀可寫 |
ios:: out | ios::binary | 以二進位制方式開啟一個輸出檔案 |
ios::in l ios::binar | 以二進位制方式開啟一個輸入檔案 |
注意點:
1)每一個開啟的檔案都有一個檔案指標,該指標的初始位置由I/O方式指定,每次讀寫都從檔案指標的當前位置開始。每讀入一個位元組,指標就後移一個位元組
2)可以用“位或”運算子“|”對輸入輸出方式進行組合但是不能組合互斥的方式
3)如果開啟操作失敗,open函式的返回值為0(假),如果是用呼叫建構函式的方式開啟檔案的,則流物件的值為0。可以據此測試開啟是否成功。如
if(!outfile.open("f1.bat", ios::app) )
cout<<"open error";
向二進位制檔案中寫入類物件,並且讀取#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class Data
{
private:
int m_a;
string m_b;
float m_c;
public:
Data(int a, string b, float c) :m_a(a), m_b(b), m_c(c){}
void show()
{
cout << "m_a:" << m_a << " , m_b:" << m_b << " , m_c:" << m_c << endl;
}
};
int main()
{
/*輸出*/
ofstream out("myclass.dat", ios::app | ios::binary);
if (out.is_open()!=true)
{
cout << "can not open myclass.dat " << endl;
exit(1);
}
Data *dataArray[5];
dataArray[0] = new Data(0, "hello0", 0.0);
dataArray[1] = new Data(1, "hello1", 1.0);
dataArray[2] = new Data(2, "hello2", 2.0);
dataArray[3] = new Data(3, "hello3", 3.0);
dataArray[4] = new Data(4, "hello4", 4.0);
out.write((char *)dataArray[0], sizeof(*dataArray[0]));
out.write((char *)dataArray[1], sizeof(*dataArray[0]));
out.write((char *)dataArray[2], sizeof(*dataArray[0]));
out.write((char *)dataArray[3], sizeof(*dataArray[0]));
out.write((char *)dataArray[4], sizeof(*dataArray[0]));
out.close();
system("pause");
}
int main1()
{
/*輸入*/
ifstream in("myclass.dat", ios::binary);
if (in.is_open() != true)
{
cout << "can not open" << endl;
exit(0);
}
Data *dataArray[5] ;
dataArray[0] = new Data(0,"",0);
dataArray[1] = new Data(0, "", 0);
dataArray[2] = new Data(0, "", 0);
dataArray[3] = new Data(0, "", 0);
dataArray[4] = new Data(0, "", 0);
in.read((char *)dataArray[0], sizeof(*dataArray[0]));
in.read((char *)dataArray[1], sizeof(*dataArray[0]));
in.read((char *)dataArray[2], sizeof(*dataArray[0]));
in.read((char *)dataArray[3], sizeof(*dataArray[0]));
in.read((char *)dataArray[4], sizeof(*dataArray[0]));
(*dataArray[0]).show();
(*dataArray[1]).show();
(*dataArray[2]).show();
(*dataArray[3]).show();
(*dataArray[4]).show();
in.close();
system("pause");
}