C++ filebuf 類
示例
使用 filebuf
物件建立檔案
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// Create a file
filebuf MyFileBuf;
MyFileBuf.open("filename.txt", ios_base::out);
// Write into the file
MyFileBuf.sputn("Hello World!", 12);
// Close the file
MyFileBuf.close();
}
定義和用法
filebuf
類用於讀寫檔案。在 fstream
、ifstream
和 ofstream
類內部會使用一個 filebuf
物件。
filebuf
類定義在 <fstream>
標頭檔案中。
檔案處理函式
檔案處理函式用於開啟和關閉檔案。
open()
open(filepath, mode)
方法開啟 filepath 指定路徑的檔案。如果檔案已開啟,則此方法無效。mode 引數是一組標誌,指示檔案將如何使用。以下標誌可用於 mode 引數:
ios_base::in
- 檔案以讀取方式開啟。ios_base::out
- 檔案以寫入方式開啟。ios_base::binary
- 檔案內容被視為二進位制資料而不是文字。ios_base::ate
- 檔案在開啟時檔案指標指向檔案末尾。ios_base::app
- 新資料始終寫入檔案末尾。ios_base::trunc
- 檔案內容在開啟時立即刪除。
可以使用 |
運算子組合標誌。例如,要同時以讀取和寫入方式開啟檔案,請使用 ios_base::in|ios_base::out
。
filebuf MyFileBuf;
MyFileBuf.open("filename.txt", ios_base::in|ios_base::out);
is_open()
is_open()
方法返回一個布林值:如果檔案已開啟,則為 true;如果沒有開啟檔案,則為 false。
filebuf MyFileBuf;
cout << MyFileBuf.is_open(); << "\n"; // Displays 0 because the file is not open
MyFileBuf.open("filename.txt");
cout << MyFileBuf.is_open(); << "\n"; // Displays 1 because the file is open
close()
close()
方法關閉檔案。完成檔案操作後關閉檔案以釋放資源是一個好習慣。
MyFileBuf.close();
檔案指標函式
檔案指標是內部變數,用於指示在檔案的何處進行讀取或寫入。
檔案指標函式用於操作檔案指標。有一個**讀取**檔案指標和一個**寫入**檔案指標,但對於普通檔案,filebuf
類對兩者使用相同的指標,因此更改其中一個也會更改另一個。
pubseekpos()
pubseekpos(position, pointer)
方法將檔案指標移動到相對於檔案開頭指定的某個位置,並返回新位置。pointer 屬性使用以下標誌指定是移動讀取指標、寫入指標還是兩者都移動:
ios_base::in
- 移動讀取指標。ios_base::out
- 移動寫入指標。
可以使用 |
運算子組合這兩個標誌,如下所示:ios_base::in|ios_base::out
cout << MyFileBuf.pubseekpos(4, ios_base::in);
pubseekoff()
pubseekoff(offset, origin, pointer)
根據指定的 origin 移動檔案指標到由 offset 指定的某個位置,並返回新位置。
origin 引數必須是以下值之一:
ios_base::beg
- 相對於檔案開頭的偏移量。ios_base::cur
- 相對於當前檔案指標位置的偏移量。ios_base::end
- 相對於檔案末尾的偏移量。
pointer 屬性使用以下標誌指定是移動讀取指標、寫入指標還是兩者都移動:
ios_base::in
- 移動讀取指標。ios_base::out
- 移動寫入指標。
可以使用 |
運算子組合這兩個標誌,如下所示:ios_base::in|ios_base::out
cout << MyFileBuf.pubseekoff(-5, ios_base::end, ios_base::in);
檔案讀取函式
in_avail()
in_avail()
方法返回檔案中可供讀取的字元數。
cout << MyFileBuf.in_avail();
snextc()
snextc()
方法將檔案指標向前移動一個字元,並返回新位置的字元的 ASCII 值。
cout << MyFileBuf.snextc();
sbumpc()
sbumpc()
方法返回當前位置的字元的 ASCII 值,並將檔案指標向前移動一個字元。
cout << MyFileBuf.sbumpc();
sgetc()
sgetc()
方法返回當前位置的字元的 ASCII 值,而不移動檔案指標。
cout << MyFileBuf.sgetc();
sgetn()
sgetn(destination, n)
方法從檔案中讀取 n 個字元,並將它們寫入 destination 引數指定的 char
陣列。此方法返回讀取的字元數。
char destination[20];
int amount = MyFileBuf.sgetn(destination, 19);
destination[amount] = '\0'; // Add a null terminating character to the string
cout << destination;
檔案寫入函式
sputc()
sputc()
方法在當前位置寫入一個字元,然後將檔案指標向前移動一個字元。此方法返回寫入字元的 ASCII 值。
cout << MyFileBuf.sputc();
sputn()
sputn(source, n)
方法將 source 引數指定的 char
陣列中的 n 個字元寫入檔案。檔案指標向前移動 n 個字元。此方法返回寫入檔案的字元數。
char source[] = "Hello World!";
int num = MyFileBuf.sputn(source, 12);
cout << num << " characters were written to the file";