0

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 ?

billz
  • 44,644
  • 9
  • 83
  • 100
John Oldman
  • 89
  • 2
  • 8

2 Answers2

2

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();
Nate Kohl
  • 35,264
  • 10
  • 43
  • 55
0

You can use is_open for this. See here:

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

Stuart Golodetz
  • 20,238
  • 4
  • 51
  • 80