c++ 文件的输入与输出

(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

}

 

 

 

你可能感兴趣的:(c++ 文件的输入与输出)