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

简介: #include #include #includeusing namespace std;//追加方式写文件void writefile(){ fstream f("try.
#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;
}

相关文章
|
3天前
|
存储 编译器 C语言
c++的学习之路:5、类和对象(1)
c++的学习之路:5、类和对象(1)
19 0
|
17天前
|
人工智能 机器人 C++
【C++/Python】Windows用Swig实现C++调用Python(史上最简单详细,80岁看了都会操作)
【C++/Python】Windows用Swig实现C++调用Python(史上最简单详细,80岁看了都会操作)
|
3天前
|
C++
c++的学习之路:7、类和对象(3)
c++的学习之路:7、类和对象(3)
19 0
|
2天前
|
设计模式 Java C++
【C++高阶(八)】单例模式&特殊类的设计
【C++高阶(八)】单例模式&特殊类的设计
|
2天前
|
编译器 C++
【C++基础(八)】类和对象(下)--初始化列表,友元,匿名对象
【C++基础(八)】类和对象(下)--初始化列表,友元,匿名对象
|
6天前
|
存储 安全 C语言
【C++】string类
【C++】string类
|
存储 编译器 Linux
标准库中的string类(中)+仅仅反转字母+字符串中的第一个唯一字符+字符串相加——“C++”“Leetcode每日一题”
标准库中的string类(中)+仅仅反转字母+字符串中的第一个唯一字符+字符串相加——“C++”“Leetcode每日一题”
|
8天前
|
编译器 C++
标准库中的string类(上)——“C++”
标准库中的string类(上)——“C++”
|
8天前
|
编译器 C++
自从学了C++之后,小雅兰就有对象了!!!(类与对象)(中)——“C++”
自从学了C++之后,小雅兰就有对象了!!!(类与对象)(中)——“C++”
|
8天前
|
存储 编译器 C++
自从学了C++之后,小雅兰就有对象了!!!(类与对象)(上)——“C++”
自从学了C++之后,小雅兰就有对象了!!!(类与对象)(上)——“C++”

热门文章

最新文章