So I check the return value of ftell() and if that is negative
This is the wrong test for text files as "For a text stream, its file position indicator contains unspecified information". On error, ftell()
returns -1. With a text file, ftell()
may return some other negative number, even on success.
long position = ftell(stream);
// if (position < 0) Error(); // Weak
if (position == -1) Error(); // Better test
The standard C library does not define that errno
is set on an ftell()
error. As OP's question is tagged linux, that OS offers various conditions for setting errno
on an ftell()
error. Then when errno
is set by ftell()
, -1 is returned.
ftell()
... shall return -1, and set errno
to indicate the error.
// Remains a good test on *nix.
if (position == -1) Error(); // Better test
Yet OP has concern "it is possible to return the value of -1 (ftell() failure) even if on success,"
This is an extreme case where the file is exceptional long yet still legitimate. As the return value is long
, the file length is expected to exceed 2G.
// *nix systems
errno = 0;
if (position == -1 && errno) {
Error(); // Better *nix test
}
Many systems today that support such large files also employ a 64-bit long
, negating the need for this && errno
test (until files lengths exceed about 9,000,000,000,000,000,000 bytes - maybe 20 years).