C++ I/O 系統以 `stream` 為核心,檔案操作透過 `fstream`、`ifstream` (輸入)、`ofstream` (輸出) 實現。本文詳細說明開啟模式、讀寫方法(文字/二進位)、定位、錯誤處理等完整用法。
void open(const char* filename,
ios_base::openmode mode = ios_base::in | ios_base::out,
int protection = 0); // protection 僅限特定平台
| 旗標 | 說明 | |
|---|---|---|
| `ios::in` | 讀取模式 (ifstream 預設) | |
| `ios::out` | 寫入模式 (ofstream 預設) | |
| `ios::app` | 附加模式,寫入前定位到檔案尾 | |
| `ios::ate` | 開啟後立即定位到檔案尾 | |
| `ios::trunc` | 截斷既有檔案長度為 0 | |
| `ios::binary` | 二進位模式 (預設為文字模式) | |
| `ios::nocreate` | 檔案不存在則開啟失敗 (非標準,舊版相容) | |
| `ios::noreplace` | 檔案存在則開啟失敗 (非標準) |
| 控制子 | 功能 | 適用 |
|---|---|---|
| `dec` / `hex` / `oct` | 10/16/8 進位輸出/輸入 | 輸入/輸出 |
| `endl` | 換行並刷新緩衝區 | 輸出 |
| `ends` | 插入空字元 `\0` | 輸出 |
| `setprecision(n)` | 設定浮點數精度 | 輸出 |
| `fixed` / `scientific` | 固定/科學記號浮點格式 | 輸出 |
| `setw(n)` / `setfill(c)` | 欄寬/填補字元 | 輸出 |
out.put('A'); // 寫入單一字元
char ch; in.get(ch); // 讀取單一字元到參考
int c = in.get(); // 回傳 int,EOF 為 -1
in.get(buf, 128, '\n'); // 讀取一行到字元陣列
// 寫入結構體陣列
struct Record { int id; double score; };
Record recs[100];
out.write(reinterpret_cast(recs), sizeof(recs));
// 讀取
in.read(reinterpret_cast(recs), sizeof(recs));
streamsize actual = in.gcount(); // 實際讀取位元組數
while (!in.eof()) { ... } // 不推薦,易多讀一次
while (in.read(buf, sizeof(buf))) { ... } // 推薦:以讀取操作本身為判斷
兩個獨立指標:讀指標 (get pointer)、`seekg()`;寫指標 (put pointer)、`seekp()`。
in.seekg(100, ios::beg); // 讀指標從開頭偏移 100 bytes
out.seekp(0, ios::end); // 寫指標移至檔案尾
in.seekg(-50, ios::cur); // 從目前位置向前 50 bytes
定位基準:`ios::beg` (開頭)、`ios::cur` (目前)、`ios::end` (結尾)。
| 函式 | 含義 |
|---|---|
| `good()` | 無錯誤 (eof/fail/bad 皆 false) |
| `eof()` | 已到檔案尾 |
| `fail()` | 邏輯錯誤 (如格式不符) |
| `bad()` | 系統層級錯誤 (硬碟故障等) |
| `rdstate()` | 取得完整狀態旗標位元組合 |
| `clear()` / `setstate()` | 清除/設定狀態旗標 |
#include
#include
#include
using namespace std;
struct Student { int id; char name[20]; float gpa; };
void writeRecord(const string& file, const Student& s)
{
ofstream out(file, ios::binary | ios::app);
out.write(reinterpret_cast(&s), sizeof(s));
}
bool readRecord(const string& file, int index, Student& s)
{
ifstream in(file, ios::binary);
in.seekg(index * sizeof(Student), ios::beg);
return in.read(reinterpret_cast(&s), sizeof(s));
}
int main()
{
Student s1 = {1, "Alice", 3.8f};
writeRecord("students.dat", s1);
Student s2;
if (readRecord("students.dat", 0, s2))
cout << s2.name << " " << s2.gpa << endl;
}
掌握 `ifstream`/`ofstream`/`fstream` 開啟模式、文字與二進位讀寫介面、定位與錯誤處理,即可靈活應對各類檔案操作需求。二進位模式下善用 `read`/`write` 搭配 `reinterpret_cast` 處理結構體/陣列,是高效能資料持久化關鍵。