隨機訪問流, 使用mark(標記)標注流的位置, 包含兩種方法tell和seek;
tell, 是返回流mark的位置, 包含g和p兩種版本.g表示get, 指輸入流; p表示put, 指輸出流;
seek, 是跳至流mark所指的位置, 也包含g和p兩種版本;seek可以指定位置, 也可以指定偏移(offset);
代碼如下:
/*
* cppprimer.cpp
*
* Created on: 2013.11.28
* Author: Caroline
*/
/*eclipse cdt, gcc 4.8.1*/
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
int main()
{
std::fstream inOut("copyOut", std::fstream::ate/*末尾*/ | std::fstream::in | std::fstream::out);
if(!inOut) {
std::cerr << "Unable to open file! " << std::endl;
return EXIT_FAILURE;
}
std::fstream::pos_type end_mark = inOut.tellg();
inOut.seekg(0, std::fstream::beg); //重定位在起點
std::size_t cnt(0);
std::string line;
while (inOut && inOut.tellg() != end_mark &&
getline(inOut, line))
{
cnt += line.size() + 1;
std::fstream::pos_type mark = inOut.tellg(); //記住當前位置
inOut.seekp(0, std::fstream::end); //跳至末尾
inOut << cnt;
if (mark != end_mark) inOut << " "; //除了最後一行, 均寫入空格
inOut.seekg(mark); //回到記錄的地點
}
inOut.seekp(0, std::fstream::end);
inOut << "\n";
return 0;
}