...
Consequently, the return value of ftell() for streams opened in text mode should never be used for offset calculations other than in calls to fseek().
POSIX [Open Group 2008IEEE Std 1003.1:2013] provides several guarantees that the problems described in the C Standard do not occur on POSIX systems.
First, the fopen() page page says:
The character '
b' shall have no effect, but is allowed for ISO C standard conformance.
This guarantees that binary files are treated the same as text files in POSIX.
Second, the fwrite() page page says:
For each object, size calls shall be made to the fputc() function, taking the values (in order) from an array of unsigned char exactly overlaying the object. The file-position indicator for the stream (if defined) shall be advanced by the number of bytes successfully written.
...
Understanding the difference between text mode and binary mode with file streams is critical when working with functions that operate on them. Setting the file position indicator to end-of-file with fseek() has undefined behavior for a binary stream. In addition, the return value of ftell() for streams opened in text mode is useful only in calls to fseek(), not for determining file sizes or for any other use. As such, fstat() or other platform-equivalent functions should be used to determine the size of a file.
Recommendation | Severity | Likelihood | Detectable |
|---|
Repairable | Priority | Level |
|---|---|---|
FIO19-C | Low | Unlikely |
Yes | Yes |
P2
P3 | L3 |
Automated Detection
Tool | Version | Checker | Description | ||||||
|---|---|---|---|---|---|---|---|---|---|
| LDRA tool suite |
| 44 S | Enhanced Enforcement |
Bibliography
| [IEEE Std 1003.1:2013] | XSH, System Interfaces, fopenXSH, System Interfaces, fwrite |
| [ISO/IEC 9899:2011] | Section 7.21.3, "Files" Section 7.21.9.2, "The fseek Function"Section 7.21.9.4, "The ftell Function" |
| [MSDN] | "ftell" |
...
...