Namespaces
Variants
Views
Actions

Talk:cpp/io/basic ifstream/close

From cppreference.com
< Talk:cpp‎ | io

example for open, is_open and close

#include <fstream>
#include <iostream>
 
using namespace std;
 
int main (int argc, char *argv[])
{
	// could start with index is always prog name
	cout<<"usage: "<< argv[0] <<" <filename>\n";
	if(argc > 1) {
		char *pFilename = argv[1];
		cout<<"usage: "<< pFilename <<" <filename>\n";
		// We assume argv[1] is a filename to open
		ifstream the_file(pFilename);
		// Always check to see if file opening succeeded
		if(!the_file.is_open()) {
			cout<<"Could not open file\n";
		}
		else {
			char x;
			// the_file.get ( x ) returns false if the end of the file
			// is reached or an error occurs
			while (the_file.get(x)) {
				cout<< x;
			}
		}
		the_file.close();
	}
	return 0;
}

Jtaim (talk) 20:55, 14 November 2015 (PST)

For close, I'd rather see a use where it is distinguishable from normal destruction; that is, where the result (stream status/exception) is consumed. --Cubbi (talk) 06:27, 15 November 2015 (PST)