文件流

#include <fstream>
#include <iostream>
#include <string>

//输入流和输出流

void test()
{  
	ifstream ifs("Point.cc");//输入流,Point.cc是路径文件名
	
	 //对于文件输入流而言,当文件不存在就打开失败
	//当文件存在的时候,才能进行正常的操作
	if (!ifs.good())
	{
		std::cerr << "ifs stream is not good" << endl;
		return;
	}

	//默认情况下,对于文件输出流而言,当文件不存在的时候,就创建文件
	//如果文件存在,就清空文件,然后再去进行写操作
	ofstream ofs("wuhan.txt"); //输出流
	if (!ofs.good())
	{
		std::cerr << "ofs ofstream not good " << endl;
		ifs.close();
		return;
	}

	string line;
	//ifs >> line; 默认以空格为分割读
	while (getline(ifs , line))	 //按行读文件
	{
		ofs << line << endl;
	}
	ifs.close();
	ofs.close();
}
//输入输出流


void test2()
{
	
	string filename("test.txt");
	fstream fs(filename); //文件输入输出流	
	//对于文件输入输出流而言,当文件不存在的时候就打开失败
	if (!fs.good())
	{
		std::cerr << "fs fstream is not good" << endl;
		return;
	}

	int number = 0;
	for (size_t idx = 0; idx != 5; ++idx)
	{
		std::cin >> number;
		fs << number << " ";
	}

	cout << "pos = " << fs.tellp() << endl;	//tellp():返回下一次想访问的位置

	/* fs.seekp(0); */	   //输入指针偏移到0的位置
	/* fs.seekp(0, std::ios::beg); */  //和上一句代码等价,相对于beg偏移0

	number = 10;
	for (size_t idx = 0; idx != 5; ++idx)
	{
	   cout << "fs.good() = " << fs.good() << endl 
	        << "fs.eof() = " << fs.eof() << endl 
	        << "fs.fail() = " << fs.fail() << endl; 

		//当流出问题时,fs无法输出数据到number
		fs >> number;//文件指针已经到末尾,流出问题
		cout << number << " ";
	}
	cout << endl;
	fs.close();
}
输入流使用:seekp()、tellg()
输出流使用: seekg()、tellp()

流的打开方式
输入流:
ifstream ifs("test.txt",std::ios::in);//第二个参数没写时,默认就是输入模式
ifstream ifs("test.txt",std::ios::a'te);//追加模式


输出流:
std::ofstream ofs("text1.txt", std::ios::app); //末尾模式,接在文件末尾写
std::ofstream ofs("text1.txt", std::ios::out); //第二个参数没写时,默认就是输出模式,会先清空再写


 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值