17
2014
03

c++中fstream类对文本文件的操作

code:

#include <iostream>
#include <string> 
#include<fstream>
using namespace std;
//追加方式写文件
void writefile()
{
fstream f("try.txt",ios::out|ios::app);
if(!f){
    cout<<"File open error!\n";
    return;
}
f<<123<<" "<<456<<" "<<"my name is aa\n";
f.close();
}
//读取文件
void readfile()
{
fstream f("try.txt",ios::in);
if(!f){
    cout<<"File open error!\n";
    return;
}
int a,b;
char s[20];
while(1)
{
a=0;b=0;
s[0]=0;
 f>>a>>b;
 f.getline(s,20);
 if(a==0) break;//循环读取数据,没有数据时退出
 cout<<a<<" "<<b<<" "<<s<<endl;
}
f.close();
}
///复制文件二进制数据
void copybinary()
{
ifstream fin("try1.txt",ios::in|ios::binary);
  if(!fin){
    cout<<"File open error!\n";
    return;
  }
  ofstream fout("try2.txt",ios::out|ios::binary);
  char c[1024];
  int count=0;
  while(!fin.eof())
  {
    fin.read(c,1024);
count=fin.gcount();
for(int i=0;i<count;i++)
{
c[i]=255-c[i];//字节取反,可以实现程序加密,让别人打不开,自己知道哪个字节少了多少,再还原
}
    fout.write(c,count);
  }
  fin.close();
  fout.close();
  cout<<"Copy over!\n";
}
int main()
{
/*writefile();
readfile();*/
copybinary();
return 0;
}




版权声明:
作者:真爱无限 出处:http://www.pukuimin.top 本文为博主原创文章版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接.
« 上一篇下一篇 »

相关文章:

评论列表:

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。