初识c++(16)之c++中的读写文件(fstream)

先上代码:

#include<iostream>
#include<fstream>

using namespace std;

int main(){
	string str;
	int n;
	int m;
	ofstream outfile("my_file.txt");
	if(outfile){
			outfile << "helloworld!" << " " << 1 << " " << 2 << endl;
			outfile << "hello!" << " " << 3 << " " << 4 << endl;
			outfile << "world!" << " " << 5 << " " << 6 << endl;
	}
	else{
		cout << "error:failed to open file!" << endl;
	}
	
	ifstream infile("my_file.txt");
	
	while(infile >> str){
		infile >> n;
		infile >> m;
		cout << str << "  " << n << "  " << m << endl;
	}
	
	return 0;
}

结果:

helloworld!  1  2
hello!  3  4
world!  5  6

解释:

上面的代码主要用了两个类,ofstream和ifstream,都存在头文件#include<fstream>里。

ofstream outfile("my_file.txt");

这句话的作用就是,定义一个名叫outfile的对象,并打开“my_file。txt”文件,如果程序找不到这个文件就会新建这个文件,这种打开文件的方式会将文件之前的内容给全部清空,如果想要保留文件的内容,并且添加新的内容,就需要用append模式,应该这样写:

ofstream outfile("my_file.txt",ios_base::app);

如果成功打开文件,outfile = true,如果打开失败,outfile = flase.写文件的操作类似于std::cout的操作。

值得注意的是,endl,会插入一个换行。

if(outfile){
			outfile << "helloworld!" << " " << 1 << " " << 2 << endl;
			outfile << "hello!" << " " << 3 << " " << 4 << endl;
			outfile << "world!" << " " << 5 << " " << 6 << endl;
	}
	else{
		cout << "error:failed to open file!" << endl;
	}

对于读文件,;类似于std::cin的操作,值得注意的是,infile >> str ,返回的是写入的字符,文档结尾为0,返回的也是0

ifstream infile("my_file.txt");
	
	while(infile >> str){
		infile >> n;
		infile >> m;
		cout << str << "  " << n << "  " << m << endl;
	}

 

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值