随时机见流, 利用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;
}
输出(文本):
Caroline Wendy Spike Winny 9 12 16 21
作者:csdn博客 Spike_King
