原文連結
前言:
c++的檔案流處理其實很簡單,前提是你能夠理解它。檔案流本質是利用了一個buffer中介層。有點類似標準輸出和標準輸入一樣。
c++ IO的設計保證IO效率,同時又兼顧封裝性和易用性。本文將會講述c++檔案流的用法。
有錯誤和疏漏的地方,歡迎批評指證。
需要包含的標頭檔: <fstream>
名字空間: std
也可以試用<fstream.h>
fstream提供了三個類,用來實現c++對檔案的操作。(檔案的建立,讀寫)。
ifstream -- 從已有的檔案讀
ofstream -- 向檔案寫內容
fstream - 開啟檔案供讀寫
支援的檔案類型
實際上,檔案類型可以分為兩種: 文字檔和二進位檔案.
文字檔儲存的是可讀的字元, 而二進位檔案儲存的只是位元據。利用二進位模式,你可以操作映像等檔案。用文字模式,你只能讀寫文字檔。否則會報錯。
例一: 寫檔案
聲明一個ostream變數
- 調用open方法,使其與一個檔案關聯
- 寫檔案
- 調用close方法.
- #include <fstream.h>
-
- void main
- {
- ofstream file;
-
- file.open("file.txt");
-
- file<<"Hello file/n"<<75;
-
- file.close();
- }
可以像試用cout一樣試用操作符<<向檔案寫內容.
Usages:
-
- file<<"string/n";
- file.put('c');
例二: 讀檔案
1. 聲明一個ifstream變數.
2. 開啟檔案.
3. 從檔案讀資料
4. 關閉檔案.
- #include <fstream.h>
-
- void main
- {
- ifstream file;
- char output[100];
- int x;
-
- file.open("file.txt");
-
- file>>output;
- cout<<output;
- file>>x;
- cout<<x;
-
- file.close();
- } 同樣的,你也可以像cin一樣使用>>來操作檔案。或者是調用成員函數Usages:
-
- file>>char *;
- file>>char;
- file.get(char);
- file.get(char *,int);
- file.getline(char *,int sz);
- file.getline(char *,int sz,char eol);
1.同樣的,你也可以使用建構函式開開啟一個檔案、你只要把檔案名稱作為建構函式的
第一個參數就可以了。
- ofstream file("fl.txt");
- ifstream file("fl.txt");
上面所講的ofstream和ifstream只能進行讀或是寫,而fstream則同時提供讀寫的功能。
void main()
- {
- fstream file;
-
- file.open("file.ext",iso::in|ios::out)
-
- //do an input or output here
-
- file.close();
- }
open函數的參數定義了檔案的開啟模式。總共有如下模式
- 屬性列表
-
- ios::in 讀
- ios::out寫
- ios::app從檔案末尾開始寫
- ios::binary 二進位模式
- ios::nocreate開啟一個檔案時,如果檔案不存在,不建立檔案。
- ios::noreplace開啟一個檔案時,如果檔案不存在,建立該檔案
- ios::trunc開啟一個檔案,然後清空內容
- ios::ate開啟一個檔案時,將位置移動到檔案尾
Notes
- 預設模式是文本
- 預設如果檔案不存在,那麼建立一個新的
- 多種模式可以混合,用|(按位或)
- 檔案的byte索引從0開始。(就像數組一樣)
我們也可以調用read函數和write函數來讀寫檔案。
檔案指標位置在c++中的用法:
- ios::beg檔案頭
- ios::end檔案尾
- ios::cur當前位置例子:
- file.seekg(0,ios::end);
-
- int fl_sz = file.tellg();
-
- file.seekg(0,ios::beg);
常用的錯誤判斷方法:
- good()如果檔案開啟成功
- bad()開啟檔案時發生錯誤
- eof()到達檔案尾例子:
- char ch;
- ifstream file("kool.cpp",ios::in|ios::out);
-
- if(file.good()) cout<<"The file has been opened without problems;
- else cout<<"An Error has happend on opening the file;
-
- while(!file.eof())
- {
- file>>ch;
- cout<<ch;
- }