C++详解(5) 文件流对象的使用

  • 写文件
#include <iostream>
#include <fstream>

using namespace std;

int main()
{
	ofstream outfile("test.txt"); // 创建一个名为test.txt的文件
	outfile << "hello file"; // 向文件中写入hello file
	outfile.close(); // 关闭文件流对象
	
	return 0;
}
  • 读文件
#include <iostream>
#include <fstream>
#include <string>

int main()
{
	// 提前创建one.txt文件,并在里面输入一些文字
	ifstream infile("one.txt");  // 读one.txt
	while(infile >> s)  // 循环读
		cout << s << endl; 
	infile.close();  //关闭文件流对象
	
	return 0;
}
  • 文件绑定(2种)
#include <iostream>
#include <fstream>
#include <string>

int main()
{
	// 第一种方法 直接绑定
	ifstream infile("one.txt");
	// 第二种方法 open()绑定 
	ifstream infile2;  // 定义一个文件流对象
	string file("one.txt") // 定义一个string 类型的字符串 one.txt
	infile2.open(file) // ERROR:open()中的参数只支持C风格的字符串
	infile2.open(file.c_str()); // right 把字符串转换成C风格 
	inflie2.open("one.txt"); // 同 infile2.open(file.c_str())
	
	// 记得关闭文件流
	return 0;
}
  • 判断打开文件是否成功
#include <iostream>
#include <fstream>
#include <string>

int main()
{
	string file("one.txt");  // 同上
	ifstream infile(file.c_str());  // 同上
	
	if(infile){
		cout << "success" << endl;
	} // 检查文件打开成功
	if(!infile){ // 检查文件打开失败
		cerr << "error: unable to open input file:" << file << endl;
		return -1;
	} 
	// 记得关闭文件流
	
	return 0;
}
  • 如果文件流文件错误
int main()
{
	ifstream infile("error.txt");  // 读取不存在的文件error.txt
	if(!infile){ // 检查文件打开失败
		cerr << "error: unable to open input file:" << file << endl;
	} 
	infile.close();  // 关闭文件流
	infile.clear();  // 清除文件流对象状态
	
	// 可继续后序使用infile文件流对象
}
  • demo
#include <iostream>
#include <fstream>
#include <string>
#include <vector>

using namespace std;

void process(string s)
{
	cout << s << endl;
}

int main()
{	
	// 提前创建one.txt two.txt three.txt文件 并保存一些文本内容
	vector<string> files;
	files.push_back("one.txt");
	files.push_back("two.txt");
	files.push_back("error.txt");  // 不存在的文件
	files.push_back("three.txt");
	
	string s;
	vector<string>::const_iterator it = files.begin();
	while(it != files.end())
	{
		ifstream input(it->c_str()); // 文件对象流可以一直绑定
		if(!input)
		{
			cerr << "error: can not open file << *it << endl;
			input.clear(); // 清除的错误文件流状态
			++it;
		} else {
			while(input >> s)
				process(s);
			input.close();  // 清除文件对象eof状态(看操作系统liunx 好像不需要)
			input.clear();
			++it;
		}
	}
	return 0;
}
  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值