// DemoIOSeekp.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
void viewFileContext()
{
ifstream ifs("100.txt");
std::string str;
while(ifs >> str)
{
}
cout<<"viewFileContext : = ";
cout << str;
cout<<endl;
ifs.close();
}
void printI( int i )
{
cout <<"tellp = "<<i<<endl;
}
int main()
{
int i = 0;
viewFileContext();
//如果添加 ios::app方式,经过测试发现 seekp不起作用,总是在文件末尾添加。
// 100.txt的文件初始内容:ABCDEFGHIJKLMNOPQRSTUVWXYZ
fstream x("100.txt", ios::binary | ios::out | ios::in);
x.seekp(-2,ios::end);
i = x.tellp();
printI(i);
x <<"-";
x.flush();
// ABCDEFGHIJKLMNOPQRSTUVWXYZ-
viewFileContext();
x.seekp(0,ios::beg);
i = x.tellp();
printI(i);
x <<"=";
x.flush();
// =BCDEFGHIJKLMNOPQRSTUVWXYZ-
viewFileContext();
x.seekp(10,ios::beg);
i = x.tellp();
printI(i);
x <<"*";
x.flush();
// =BCDEFGHIJ*LMNOPQRSTUVWXYZ-
viewFileContext();
x.seekp(-10,ios::end);
i = x.tellp();
printI(i);
x <<"#";
x.flush();
// =BCDEFGHIJ*LMNOPQ#STUVWXYZ-
viewFileContext();
i = 5;
x.seekp(i);
printI(x.tellp());
x <<"@";
x.flush();
// =BCDE@GHIJ*LMNOPQ#STUVWXYZ-
viewFileContext();
x.close();
}
总之, 不能在文件任意位置插入内容,使用skeep时,插入内容后,插入点后面的数据将会被覆盖。如果要实现真正的插入而不覆盖原来的内容,现在我还没想出思路来,有实现过的人呢请指教。