码迷,mamicode.com
首页 > 其他好文 > 详细

File Input and Output

时间:2015-01-27 23:14:54      阅读:343      评论:0      收藏:0      [点我收藏+]

标签:

Use of File Stream

Assume ifle and ofile is the string object storing the names of input and output files‘ namess.

string ifile = "inputFile.txt";
string ofile = "outputFile.txt";

 Then the use of file stream is like this:

// construct an ifstream and bind it to the file named ifile
ifstream infile(ifile.c_str());
// ofstream output file object to write file named ofile
ofstream outfile(ofile.c_str());

 

Also, we can define unbound input and output file stream first, and then use open function to boud the file we‘ll access:

ifstream infile;		// unbound input file stream
ofstream outfile;		// unbound output file stream

infile.open("in");		// open file named "in" in the current directory
outfile.open("out");	// open file named "out" in the current directory

 

After opening the file, we need to check if it is successful being opened: 

// check that the open succeeded
if(!infile){
	cerr << "error: unable to open input file: "
		 << infile << endl;
	
	return -1;
}

 

Rebound File Stream with New File

If we want to bound the fstream with another file, we need to close the current file first, and then bound with another file:

ifstream infile("in");		// open file named "in" for reading
infile.close();				// closes "in"
infile.open("next");		// open file named "next" for reading

 

Clear File Stream Status

Opening all file names in a string vector, one direct version is:

vector<string> files;
...
vector<string>::const_iterator it = files.begin();
string s;	// string buffer 

// for each file in the vector
while(it != files.end()){
	ifstream input(it->c_str());	// open the file
	
	// if the file is ok, read and "process" the input
	if(!input)
		break;						// error: bail out!
	while(input >> s)				// do the work on this file
		process(s);
	++it;							// increament iterator to get next file
}

 

More efficient way but with much more accurate operation version:

ifstream input;
vector<string>::const_iterator it = files.begin();

// for each file in the vector
while(it != files.end()){
	input.open(it->c_str());		// open the file
	
	// if the file is ok, read and "process" the input
	if(!input)
		break;						// error: bail out!
	while(input >> s)				// do the work on this file
		process(s);
	
	input.close();					// close file when we‘re done with it
	input.clear();					// reset state to ok
	++it;
}

 

File Input and Output

标签:

原文地址:http://www.cnblogs.com/kid551/p/4254363.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!