Home  >  Article  >  Backend Development  >  How to Reliably Determine File Size in C ?

How to Reliably Determine File Size in C ?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-21 07:46:10231browse

How to Reliably Determine File Size in C  ?

Determining File Size in C : A Reliable and Portable Approach

In C , obtaining a file's size is a crucial operation often encountered in programming tasks. To identify the most suitable method for achieving this, it is essential to consider factors such as portability, reliability, and code simplicity.

One widely employed approach is utilizing the C standard library's ifstream class. By opening a file in binary mode and specifying the ate flag, the input stream seeks to the end of the file. Subsequently, the tellg() member function can be used to retrieve the current position within the file, effectively providing the file's size.

Code Example:

#include <fstream>

std::ifstream::pos_type filesize(const char* filename) {
    std::ifstream in(filename, std::ifstream::ate | std::ifstream::binary);
    return in.tellg(); 
}

However, it is important to note that this approach has a potential caveat. tellg() does not always accurately report the file's size on certain platforms. For a more robust solution, alternative methods, such as seeking to the end of the file using seekg() and tellg() before opening the file in binary mode, might be necessary.

The provided code snippet effectively calculates the file's size based on the presumption that the file can be opened and accessed. Proper error handling mechanisms should be implemented in a production-grade application to account for potential exceptions during file opening or reading.

The above is the detailed content of How to Reliably Determine 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