Home >Backend Development >C++ >How to Get a File's Size in C : A Simple and Reliable Approach?

How to Get a File's Size in C : A Simple and Reliable Approach?

Susan Sarandon
Susan SarandonOriginal
2024-11-11 12:58:03949browse

How to Get a File's Size in C  : A Simple and Reliable Approach?

Determining File Size in C

The query "How can I obtain a file's size in C ?" prompts exploration into the most prevalent method for accomplishing this task while adhering to specific criteria.

Criteria:

  • Portable across platforms (Unix, Mac, Windows)
  • Reliable and accurate
  • Easy-to-understand and without external library dependencies

Common Approach:

Utilizing C 's native file I/O features, a common approach to determine the size of a file involves the following steps:

#include <fstream>

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

Explanation:

  1. Include the library for file I/O operations.
  2. Define a function filesize that accepts a file name as a parameter and returns the file size as std::ifstream::pos_type.
  3. Create an std::ifstream object in and open the file specified by filename in "binary" mode (std::ifstream::binary).
  4. Use std::ifstream::ate mode to position the file pointer at the end of the file.
  5. Retrieve the current file pointer position using in.tellg(), which returns the file size in bytes.
  6. Return the file size.

Additional Information:

Please note that this solution assumes the file is not open in other applications, which may affect the file size. For further details on file handling in C , refer to: http://www.cplusplus.com/doc/tutorial/files/.

The above is the detailed content of How to Get a File's Size in C : A Simple and Reliable Approach?. 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