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

c++ 文件的输入与输出

2010-11-21 11:42 337 查看
(1),ifstream,

ifstream infile(ifile.c_str()); //construct an ifstream and bind it to the file named ifile

或infile.open("in");

(2),ofstream,

ofstream outfile(ofile.c_str()); //ofstream output file object to write file named ofile

或 outfile.open("out");

(3),fstream.

检查文件打开是否成功

if(!infile) {

cerr << "error: unable to open input file : " << ifile << endl;

return -1;

}

如果程序员需要重用文件流读写多个文件,必须在读另一个文件之前调用 clear() 清除该流的状态

一个打开并检查输入文件的程序

// opens in binding to the given file

ifstream& open_file(ifstream &in, const string &file)

{

in.close(); //close in case it was already open

in.clear(); //clear any existing errors

//if the open fails, the stream will be in an invalid state

in.open(file.c_str()); //open the file we were given

return in; //condition state is good if open succeeded

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: