Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: assign cin to an ifstream variable?

You know the common stdio idiom that stdin is specified by a filename of "-", e.g.

if ((strcmp(fname, "-"))
    fp = fopen(fname);
else
    fp = stdin;

What's the best way to do this with an ifstream instance? I've received a bit of code that has an ifstream as part of a class and I'd like to add code to do the equivalent, something like:

if ( filename == "-")
    logstream = cin;  // **how do I do this*?*
else
    logstream.open( filename.c_str() );
like image 959
Mark Harrison Avatar asked Jan 29 '10 02:01

Mark Harrison


People also ask

Is Cin an ifstream?

cin is an example of an istream. ostream is a general purpose output stream. cout and cerr are both examples of ostreams. ifstream is an input file stream.

Is ifstream a variable?

An ifstream variable has an open function which can be used to open a file. The name of the file is a parameter to the open function. Once this is done, you can read from the ifstream object in exactly the same way you would read from cin.

Does ifstream inherit from istream?

File streams come in two flavors also: the class ifstream (input file stream) inherits from istream, and the class ofstream (output file stream) inherits from ostream.

What is ifstream Infile in C++?

ifstream infile ("file-name"); The argument for this constructor is a string that contains the name of the file you want to open. The result is an object named infile that supports all the same operations as cin , including >> and getline .


1 Answers

cin is not an ifstream, but if you can use istream instead, then you're in to win. Otherwise, if you're prepared to be non-portable, just open /dev/stdin or /dev/fd/0 or whatever. :-)


If you do want to be portable, and can make your program use istream, here's one way to do it:

struct noop {
    void operator()(...) const {}
};

// ...

shared_ptr<istream> input;
if (filename == "-")
    input.reset(&cin, noop());
else
    input.reset(new ifstream(filename.c_str()));

The noop is to specify a deleter that does nothing in the cin case, because, well, cin is not meant to be deleted.

like image 146
Chris Jester-Young Avatar answered Oct 10 '22 20:10

Chris Jester-Young