Home >Backend Development >C++ >Why Does `tellg()` Not Accurately Report File Size in C ?

Why Does `tellg()` Not Accurately Report File Size in C ?

Barbara Streisand
Barbara StreisandOriginal
2024-12-02 20:56:11118browse

Why Does `tellg()` Not Accurately Report File Size in C  ?

tellg() Misconception: Reporting File Size

In your code snippet, you encountered an issue where the tellg() function returned a value larger than the actual size of the file read by the read() function. This perceived discrepancy arises from a misunderstanding of tellg()'s purpose.

Tellg's Function

Contrary to popular belief, tellg() does not provide the size of the file or the offset from the beginning in bytes. Instead, it returns a token value, a placeholder that can be used later to return to the same position in the file. The actual number returned can vary depending on the operating system and file mode.

Practical Implementations

In practice, on Unix systems, tellg() returns the offset in bytes, while on Windows, it returns the offset only for files opened in binary mode. For text mode on Windows, the returned value may not accurately reflect the number of bytes required to reach that position.

Accurate Byte Counting

To accurately determine the number of bytes that can be read, the only reliable method is to perform a read operation. This can be achieved using a technique like the following:

#include <limits>

file.ignore( std::numeric_limits<std::streamsize>::max() );
std::streamsize length = file.gcount();
file.clear();   //  Since ignore will have set eof.
file.seekg( 0, std::ios_base::beg );

Other Observations

Besides the tellg() issue, your code contains additional errors:

  1. The line "buffer = new char[length];" should be "*buffer = new char[length];" to allocate a pointer to an array of characters.
  2. The loop condition in the second for loop should be while ( file.get( buffer[i] ) ) for character-by-character reading.
  3. Error handling should be implemented in case the file opening fails.

By addressing these issues, your code can accurately determine the size of the file and perform read operations as intended.

The above is the detailed content of Why Does `tellg()` Not Accurately Report File Size in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn