I am not understanding SD file.size / file.available

I have a code snippet that basically reads a file from SD in blocks and sends them to a web client. Easy right? Not so fast. It works fine with small files but runs forever on larger ones.
Looking at the documentation, I see what appears to be a discrepancy.

file.size returns the size of the file in bytes (unsigned long)
file.available returns the number of bytes available (int)
file.position returns the position within the file (unsigned long)

If I open a file that is 40KB, what should file.available return? It normally doesn’t matter as it is used as a bool (while(file.available()){read;write;}… but the 16 bits are theoretically overflowing so it could return a false zero or non-zero.

I could “fix” the library and my code to expect available as an unsigned long, or I could use while(file.position < file.size()){read;write;}

Anybody ever encounter this and how did you work around it?


Which SD library are you using? Have you thought to look at the code of that library for
further documentation or to examine what its code does?

available() is normally a call telling you what size of buffer to use for a call to read
for a buffer - it is likely to know about the maximum buffer size used by the library, not
just the size of the file remaining.
just the

file.available() returns the number of bytes in the rest of the file or 32767, whichever is smaller. In other words, it will return 32767 until you are less than 32767 bytes from the end of the file.

32767 is the largest value that can fit in a 16-bit signed integer.

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.