Musmus
Musmus

Reputation: 229

C++ ifstream and getline

I'm using an old gcc compiler, if that matters (before C++11).

I have a function with the code below:

ifstream in(file);
string line;
while (std::getline(in, line))
{

}

I just want to make sure that:

  1. I do not need to check if the file actually exists, right? Does getline know to handle this?

  2. There is no need to close the stream in the end because of RAII, right?

Upvotes: 0

Views: 1570

Answers (2)

Yiğit Aras Tunalı
Yiğit Aras Tunalı

Reputation: 428

You can see the example given in the C++ reference website here.

There are explanations for different versions of it, like C++98 and C++11.

As for answers:

  1. getline() will fail, and your code won't get into the while loop, if it fails to open the file beforehand.

  2. As you said, you don't need to close the file because of RAII.

Upvotes: 3

john
john

Reputation: 88027

Obviously getline will fail if the file doesn't exist and you will not enter the while loop.

You do not need to close the stream.

Upvotes: 0

Related Questions