Norgannon
Norgannon

Reputation: 519

std::ifstream initial value checks as true when uninitialized

I realized that when I test the value of a std::ifstream without initializing it, it checks as true.

How can I initialize my stream in a way that until I open the file I want to use, the check would return false ?

(Or maybe I should not use the value of the stream to determine if it is opened ?)

Small example to show the problem :

std::ifstream stream;

bool iWantToUseTheStream = false;

if (iWantToUseTheStream)
  stream.open(someFileName, std::fstream::in);

if (stream) // checks as true whether I opened the stream or not !
  std::cout << "I don't want this to print if I did not open the stream !";

Upvotes: 0

Views: 996

Answers (1)

NathanOliver
NathanOliver

Reputation: 180935

Instead of checking the state of the stream as a whole, you can use the is_open() member function to check if the file is open. That would make your code look like

std::ifstream stream;

bool iWantToUseTheStream = false;

if (iWantToUseTheStream)
  stream.open(someFileName, std::fstream::in);

if (stream.is_open()) // is only true if there is an open file
  std::cout << "I will only print if the file is open";

Upvotes: 1

Related Questions