首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

C++ 隨機存取流(random access stream)詳解

     編輯:關於C++

概念

隨機存取流允許任意位置讀寫,核心操作為 tellg/tellp(取得當前讀/寫位置)與 seekg/seekp(移動讀/寫位置)。位置型別為 std::fstream::pos_type。

關鍵函式

  • tellg():回傳輸入流當前位置。
  • tellp():回傳輸出流當前位置。
  • seekg(pos) / seekg(off, dir):移動輸入流位置。
  • seekp(pos) / seekp(off, dir):移動輸出流位置。
  • 方向常數:beg(開頭)、cur(目前)、end(結尾)。

程式碼示範:邊讀邊寫行長度

/* cppprimer.cpp
 * Created on: 2013.11.28
 * Author: Caroline
 */
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;

int main() {
    fstream inOut("copyOut", fstream::ate | fstream::in | fstream::out);
    if (!inOut) {
        cerr << "Unable to open file!" << endl;
        return EXIT_FAILURE;
    }
    fstream::pos_type end_mark = inOut.tellg();
    inOut.seekg(0, fstream::beg);
    size_t cnt = 0;
    string line;
    while (inOut && inOut.tellg() != end_mark && getline(inOut, line)) {
        cnt += line.size() + 1; // +1 for newline
        fstream::pos_type mark = inOut.tellg();
        inOut.seekp(0, fstream::end);
        inOut << cnt;
        if (mark != end_mark) inOut << " ";
        inOut.seekg(mark);
    }
    inOut.seekp(0, fstream::end);
    inOut << "\n";
    return 0;
}

應用場景

  • 二進位檔案隨機讀寫(資料庫索引、記錄式檔案)。
  • 需同時讀寫同一檔案(如即時日誌、緩存)。
  • 實作自訂緩衝區或記憶體映射檔案的上層封裝。

注意事項

  • 文字模式下 seekg/seekp 僅支援 tellg/tellp 回傳的位置,不可任意位移。
  • 二進位模式(std::ios::binary)可任意位移,適合固定長度記錄。
  • 讀寫切換時需呼叫 seekg/seekp 同步位置,避免緩衝區不一致。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved