【C++文件流与文件操作】

以ASCLL的形式读写文件

ifstream和ofstream是类型名,表示输入和输出文件流

ifstream file_in(fillname,openmode=ios::in);
ofstream file_out(fillname,openmode=ios::out);

参数 filename 是要打开的文件名,参数 openmode 是打开的模式,一般不用填,有默认值

ifstream 默认打开模式为 ios::in 

ofstream 默认打开模式为 ios::out

 

PS:图片来自黑马程序员

 

下面是文件操作,将 a.txt 里的内容写入到 b.txt

 

#include<iostream>
#include<fstream>
#include<string>
using namespace std;

int main(){
	
	ifstream file_in("E:\\a.txt",ios::in);   //利用构造函数创建,也可以使用open函数 ,例:file_in.open("E:\\a.txt",ios::in)
	ofstream file_out("E:\\b.txt",ios::out);  
	for(string str;getline(file_in,str);)  //从a.txt中读取一行数据 
		file_out<<str<<endl;       //将读取的数据写入b.txt 
		
	//读取完毕后	file_in的文件的光标在文件尾了,即无法再读取文件内容了 
		
	/*第2种读取方式
	   char buf[1024] = {0};
	   while(file_in >> buf){
	      cout<<buf<<endl;
	   } 
	
	  第3种读取方式
	   string buf;
	   while(getline(file_in,buf)){
	  	 cout<<buf<<endl;
	   }
	
	  第4种读取方式
	   char c;
	   while((c = file_in.get())!=EOF){
	 	 cout<<c;
	   }
	*/
	
	file_in.close();	
	file_out.close();
	
	return 0; 
} 

以ASCLL的形式读写文件

#include<iostream>
#include<fstream>
using namespace std;

class A{
	public:
		char n1[64];
		int n2;
};

//写入
void test01(){
	A a = {"Jack",10};   //系统提供的默认构造函数
	
	ofstream file;
	file.open("E:\\AAA.txt",ios::out|ios::binary);
	file.write((char *)&a,sizeof(A));
}

//读取 
void test02(){
	ifstream file;
	file.open("E:\\AAA.txt",ios::in|ios::binary);
	if(!file.is_open()){
		cout<<"open fail"<<endl;
		return ; 
	}
	A a;
	file.read((char *)&a,sizeof(a));
	cout<<a.n1<<endl<<a.n2<<endl;
}

int main(){
	test01();
	test02();
	
	return 0;
}

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值