John Oldman
John Oldman

Reputation: 99

How to make sure cin opened the file properly?

I have this code :

static std :: ifstream s_inF(argv[j]);
std :: cin.rdbuf(s_inF.rdbuf());

How can I make sure it opened the file properly and there is no problem ?

I mean I would like to write something like:

static std :: ifstream s_inF(argv[j]);
std :: cin.rdbuf(s_inF.rdbuf());
if(.....)
{
  cout << "can not open the file" << endl;
  return 0;
}
...
.....
....
cin.close();

any suggestion ?

Upvotes: 0

Views: 110

Answers (2)

Nate Kohl
Nate Kohl

Reputation: 35924

All objects that are subclasses of std::basic_ios -- like s_inF and std::cin, in your case -- have have an operator bool that returns true if the stream is ready for I/O operations.

That means you can simply test them directly, e.g.:

static std::ifstream s_inF(argv[j]);
std::cin.rdbuf(s_inF.rdbuf());
if (!s_inF)
{
  cout << "can not open the file" << endl;
  return 0;
}
// ...
cin.close();

Upvotes: 2

Stuart Golodetz
Stuart Golodetz

Reputation: 20626

You can use is_open for this. See here:

http://www.cplusplus.com/reference/fstream/ifstream/is_open/

Upvotes: 0

Related Questions