隨機存取流允許任意位置讀寫,核心操作為 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 同步位置,避免緩衝區不一致。