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);
}
1 Answer 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.
available()
returns the count of bytes available to readeof()
is true when you try to read more than the length of the filefeof()
returnstrue
only after you tried to read past the end of the file?