Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
428 views
in Technique[技术] by (71.8m points)

iostream - 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() );
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...