2

Why I can't read the last byte in the file when I use the Arduino ide code? The code in cpp is work without any mistakes. This is my code on Arduino ide:

  vector<unsigned char> text;
  unsigned char textseg;
  in_file.read(&textseg,1);
  while (in_file.available()){ 
      text.push_back(textseg);
      in_file.read(&textseg,1);
  }

And this is cpp code:

vector<unsigned char> text;
unsigned char textseg;
in_file.read(reinterpret_cast<char*>(&textseg), 1);
while (!in_file.eof())
{   text.push_back(textseg);
    in_file.read(reinterpret_cast<char*>(&textseg), 1);
} 
3
  • 1
    I would guess, the difference is caused by a differrent declaration of in_file. But, as you do not show us the declaration, it is just a guess. It is also caused by the fact, that you read the last line but do not write it the the text vector because the wihle loop ist not enter, when the last character is read. I have no explanation, why this does not happen in the second case. Perhaps because the eof is only triggered when the read method reads from an empty stream and available knows that the stream is empty without reading from it again. Aug 2, 2023 at 13:49
  • 1
    because you read it but you don't write it. you have a read before the while loop but no write after the while loop. available() returns the count of bytes available to read eof() is true when you try to read more than the length of the file
    – Juraj
    Aug 2, 2023 at 19:33
  • Are you aware that feof() returns true only after you tried to read past the end of the file? Aug 3, 2023 at 6:07

1 Answer 1

1

Your loop seems to be out-by-one. I would prefer:

  vector<unsigned char> text;
  unsigned char textseg;
  while (in_file.available()){ 
      in_file.read(&textseg,1);
      text.push_back(textseg);
  }

Why read a byte, as you did, before you know if it is available?

In the Standard C++ library, eof() is true if a read fails, however in the Arduino available() means a byte is available to be read. They are not directly swappable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.