12

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.

Neuron
  • 5,141
  • 5
  • 38
  • 59
FSMaxB
  • 2,280
  • 3
  • 22
  • 41
  • In some deleted comments you mentioned blocking. So, to be clear, there's no way to do this without blocking. – Mooing Duck May 16 '13 at 21:37
  • I think in many cases `stream.eof()` would be the best solution. See https://en.cppreference.com/w/cpp/io/basic_ios/eof for details. There may be situations though where `stream.eof()` returns false although the last character in the file has already been read. – jcsahnwaldt Reinstate Monica Mar 07 '19 at 20:06

2 Answers2

9

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)

Neuron
  • 5,141
  • 5
  • 38
  • 59
Cubbi
  • 46,567
  • 13
  • 103
  • 169
  • I thought this to be the same question as I just wanted to know how to find out if there are characters left to be read. Everything else posted in my initial question was to explain why I would want to have this information: Because I want to know if performing a read would block or not which I thought was only the cause for asking the question and not part of the question itself. As it turns out, this information is essential for solving my problem, so I should have asked another Question. So I'll leave the question as I first intended it to be (like it is now) and consider asking a new one. – FSMaxB May 16 '13 at 22:12
  • @FSMaxB As MooingDuck points out, there is no way to do this without blocking, that is, without actually reading or attempting to read and failing, the next character from the **associated character sequence** (in some deleted version you mentioned serial port) into the buffer that exists inside the ifstream object. The peeked character will remain unread, so the next read from ifstream will return it, but it will only happen after it arrives from the external device into the stream. – Cubbi May 16 '13 at 22:54
2

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?

Community
  • 1
  • 1
RichieHindle
  • 272,464
  • 47
  • 358
  • 399