您的位置:首页 > 编程语言 > C语言/C++

文件操作系列之二——(标准C++文件流)

2010-07-13 07:21 211 查看
本篇开始介绍面向对象的方式处理文件的方式,不过缺点是开始依赖操作系统和环境,如后面所述的SDK依赖于windows,而CStdioFile依赖于MFC框架语言。

标准C++中操作文件流的方式是Ifstream和Ofstream的输入流和输出流文件类。要使用他们,你可以直接包含fstream头文件,当然也可以根据需要引用他们各自的头文件。

在fstream中,最重要的操作是重载了文件输入流运算符>>和文件输出流<<运算符,当然,他还有许多其他可供我们使用的地方。下面直接使用示例说明:

读文件:

]char filename[50];
cout<<"Pleast enter the file name you want to Read:/n";
cin>>filename;
//ifstream infile(filename,ios::in);
ifstream infile;
infile.open(filename, ios::in);

//if (!infile) //也可
//{
//	cout<<"File is not exist!"<<endl;
//	return;
//}
if (!infile.is_open())
{
cout<<"File is not exist!"<<endl;
return;
}
if (infile.bad())
{
cout<<"Open File Error!"<<endl;
return;
}
while(!infile.eof())
{
char tempBuf[100];
infile>>tempBuf;
cout<<tempBuf<<endl;
}
infile.close();


写文件:

]	char filename[50];
cin>>filename;
ofstream outfile;
outfile.open(filename, ios::out);
if (outfile.bad())
{
cout<<"Create File Error!"<<endl;
return;
}

char tempBuf[100];
while(cin>>tempBuf)
{
if (tempBuf[0] == 'q')
{
break;
}

outfile<<tempBuf;
outfile<<"/n";
}
outfile.close();


代码同样很简单,不需要做太多解释,详细可参考MSDN。

使用标准C++文件流操作文件是的好处同样是显而易见的,使用方便,效率高,但危险依然伴随着这些直接操作I/O流的方式。

附,本系列示例代码
,该代码在VS2008+XPsp3下测试通过。

下一篇,开始讲述带有安全验证的文件操作方式
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐