1 fstream 可以进行读写操作
2 fstream有两个指针,一个读 一个写
移动文件读指针 fstream.seekg(int pos,ios::begin); 相对位置默认是开头 可以不写 (p -put)
移动文件写指针 fstream.seekp(int pos,ios::begin); (g -get)
2013-5-5
本来按我的理解fstream是有两个指针,但做了下实验又不是
因为我在使用seekp()之后 发现tellg()返回值是我设置的这个.
再加上write之后我发现tellg 和 tellp此时的值一样,
所以fstream是只有一个指针的,tellp和tellg的返回值其实是同一个东西.
经实验得出
seekp() 和 seekg()的效果是相同的
tellp()和tellg()的效果是相同的
3 gcount()函数依然有效,记录实际读取数量
#include <iostream>
#include <fstream>
using namespace std;
#include <cstring>
void encode (char *buf ,int bytes)
{
for(int i =0;i < bytes;i++)
{
++ *buf;
buf++;
//注意 *buf++ ++的优先级比*高
}
}
void decode (char* buf,int bytes)
{
for(int i = 0;i < bytes; i++)
{
-- *buf;
buf ++;
}
}
int main(int agrc,char *argv[])
{
//a.out 源文件 新文件
if( agrc != 3 || strcmp(argv[1],"-e") && strcmp(argv[1],"-d") )
{
cout << argv[0] << " -e|-d 文件路径" << endl;
return 0;
}
fstream f1(argv[2],ios::binary| ios::in |ios::out);
if(!f1)
{
cout << "打开文件失败" << endl;
return 1;
}
bool buf[128];
int pos1 = 0,pos2 = 0; //int 最多2G
bool end = false;
void (*pf)(char *,int) = argv[1][1]=='e' ? encode:decode ;
while(f1)
{
f1.seekg(pos1); //f1.seekg(pos1,ios::begin);
f1.read( (char *)buf, sizeof(buf) ); //如果读到文件末尾 会出错
if(!f1)
{
f1.clear();
end = true;
}
pos2 = f1.tellg();
pf((char*)buf,f1.gcount());
f1.seekp(pos1); //f1.seekp(-bytes,ios::cur);
cout.write((char*)buf,f1.gcount());
f1.write( (char*)buf, f1.gcount() );
pos1 = pos2;
if(end) break;
}
}