萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

C++ ofstream 與 ifstream 檔案串流完整操作指南

前言

C++ I/O 系統以 `stream` 為核心,檔案操作透過 `fstream`、`ifstream` (輸入)、`ofstream` (輸出) 實現。本文詳細說明開啟模式、讀寫方法(文字/二進位)、定位、錯誤處理等完整用法。

一、核心類別與運算子

  • 插入運算子 `<<`:向串流寫入資料(如 `cout << "Hello"`)
  • 擷取運算子 `>>`:從串流讀取資料(如 `cin >> x`)

二、開啟檔案

open() 成員函式原型

void open(const char* filename,
          ios_base::openmode mode = ios_base::in | ios_base::out,
          int protection = 0); // protection 僅限特定平台

常用開啟模式旗標 (ios_base::openmode)

旗標可用 `|` 組合:`ios::out | ios::binary | ios::app`

建構函式直接開啟

ifstream in("data.txt");           // 讀取文字檔
ofstream out("log.bin", ios::binary | ios::app); // 二進位附加寫入
fstream io("data.dat", ios::in | ios::out | ios::binary); // 讀寫二進位

三、關閉檔案

in.close();
out.close();
// 解構子會自動呼叫 close(),但明確關閉是好習慣

四、文字檔讀寫 (格式化 I/O)

ofstream out("text.txt");
out << "Hello " << 123 << ' ' << 3.14 << endl; // 寫入

ifstream in("text.txt");
string s; int i; double d;
in >> s >> i >> d; // 讀取,以空白字元分隔

格式化控制子

旗標說明
`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)`欄寬/填補字元輸出

五、二進位檔讀寫 (非格式化 I/O)

單一字元

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(); // 實際讀取位元組數

六、EOF 檢測

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()`清除/設定狀態旗標

九、完整範例:二進位記錄檔 CRUD

#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` 處理結構體/陣列,是高效能資料持久化關鍵。

copyright © 萬盛學電腦網 all rights reserved