C++之文件读写

本文涉及了文件流fstream的几种常用的读写操作

#include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h>
using namespace std;
int main(){
	fstream file;

	//写操作
	file.open("file_test.txt",ios::out);
	if(!file.is_open()){	//检查文件是否已打开 
		cout<<"file open fail!"<<endl;
		return 0;
	}
	file<<"File Write:"<<endl;
	//预备数据 
	char str[][0xFF]={{"first"},{"second"},{"third"}};
	int data[]={1,2,3};
//	cout<<"sizeof(str)="<<sizeof(str)<<endl;
//	cout<<"sizeof(str[0])"<<sizeof(str[0])<<endl;
//	for(int i=0;i<sizeof(str)/sizeof(str[0]);i++){cout<<str[i]<<endl;}	
	//第一种:使用<<运算符
	file<<"Type 1(<<):"<<endl;	 
	for(int i=0;i<sizeof(str)/sizeof(str[0]);i++){
		file<<str[i]<<"=";
		file<<data[i]<<endl;
	}
	file<<endl;
	file.close();
	
	//第二种:使用fstream的成员函数 
	file.open("file_test.txt",ios::app);
	file<<"Type 2(write):"<<endl;
	for(int i=0;i<sizeof(str)/sizeof(str[0]);i++){
		string deng="=";
		string t=str[i]+deng+to_string(data[i])+"\n";
//		cout<<"“ "<<t<<" ”:"<<endl<<"t.size()="<<t.size()<<endl<<"sizeof(t)="<<sizeof(t)<<endl<<endl;
//		sizeof()括号内无所谓值,只在乎类型,同一类型的传参,sizeof的结果相同,均为类型所占字节数 
		file.write(t.c_str(),t.size());
	}
	file.close();


	//读操作
	file.open("file_test.txt",ios::in);
	if(!file.is_open()){
		return 0;
	}
	
	//第一种:使用>>运算符
	cout<<">>file.tellg():"<<file.tellg()<<endl;
	while(!file.eof()){
		string str;	
		file>>str;
		cout<<str<<endl;
	}
	cout<<">>file.eof():"<<file.eof()<<endl;
	cout<<">>file.tellg():"<<file.tellg()<<endl;
	//第二种:使用fstream的成员函数
	
	file.clear();//消除eof状态
	file.seekg(0,file.beg);
	cout<<endl<<"get():"<<endl;
	cout<<"get::file.tellg():"<<file.tellg()<<endl;
	while(!file.eof()){
		char t;
		if(!file.get(t)){//非常重要!!!解决了由于eof()函数返回值滞后,而导致最后一个字符重复读取的error! 
			break;
		}
		cout<<t<<endl;
	}
	cout<<"end::get::file.tellg():"<<file.tellg()<<endl;
	
	file.clear();
	file.seekp(0,file.beg);
	cout<<endl<<"getline():"<<endl;
	file.seekg(0);
	cout<<"file.tellg():"<<file.tellg()<<endl;
	while(!file.eof()){
		string str;
		if(!getline(file,str))
		{
			break;
		}
//		getline(file,str);
		cout<<str<<endl;
	}
	
	return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值