Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ std::ifstream: check if characters are left to read

Is there a way to check if any characters are left in an ifstream to read and if yes, how can I do this. If you know for sure that this isn't possible, please tell me so.

like image 978
FSMaxB Avatar asked May 16 '13 20:05

FSMaxB


2 Answers

To get what you're asking about after the edit, you can use the peek() function:

Given an std::ifstream called f

if (f && f.peek() == EOF)
    std::cout << "Nothing left to read\n";
else
    std::cout << "There is something to read or the stream is bad\n";

But keep in mind that this is not a 'more general' question, it is a different question (that is, applying this to your original question would be an error)

like image 80
Cubbi Avatar answered Nov 12 '22 12:11

Cubbi


You should put the read operation in your while condition:

while(stream >> buffer) {
    ...

That will read until the stream is empty or another error occurs.

...but if you really are trying to read one character at a time, you should read this: Reading a single character from an fstream?

like image 2
RichieHindle Avatar answered Nov 12 '22 12:11

RichieHindle