对磁盘文件进行读写操作

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

using namespace std;

ofstream & openFile(ofstream &out,const string &fileName)
{
	//打开文件作写操作
	out.close();
	out.clear();
	out.open(fileName.c_str());
	return out;
}

ifstream & openFile(ifstream &in,const string &fileName)
{
	//打开文件作读操作
	in.close();
	in.clear();
	in.open(fileName.c_str());
	return in;
}

ostream & write(ostream &out)
{
	//向磁盘文件中写入数据
	int ival;
	cout<<"\nEnter some integers:"<<endl;

	while(cin>>ival)
		out<<ival<<endl; //从键盘读入数据,写入磁盘文件中
	return out;
}

istream & read(istream &in)
{
	//读取磁盘中的数据
	int data;
	cout<<"\nThe data in disk file is:"<<endl;
	while(in>>data)
		cout<<data<<endl;  //从磁盘中读取数据,写到终端屏幕上
	return in;
}

int main()
{
	string fileName;
	cout<<"\nEnter file name:"<<endl;
	cin>>fileName;

	//写操作
	ofstream outFile;
	openFile(outFile,fileName);
	write(outFile);

	//读操作
	ifstream inFile;
	openFile(inFile,fileName);
	read(inFile);
	inFile.close();

	return 0;
}

zhaobin@debian:~$ vim x.cc
zhaobin@debian:~$ g++ -o x x.cc
zhaobin@debian:~$ ./x

Enter file name:
yyy

Enter some integers:
9 3 66 1

The data in disk file is:
9
3
66
1

你可能感兴趣的:(C++,读写操作,ifstream,ofstream)