Home > Backend Development > C++ > How can I efficiently determine the size of a file in C ?

How can I efficiently determine the size of a file in C ?

Patricia Arquette
Release: 2024-11-15 14:06:03
Original
348 people have browsed it

How can I efficiently determine the size of a file in C  ?

Retrieving File Size in C

In C , determining the size of a file is a crucial task for various applications. Among the available approaches, a commonly used and cross-platform method involves utilizing the fstream library. This solution proves reliable, straightforward, and devoid of external library dependencies.

To determine the file size, the filesize function is employed, which accepts a file path as its argument. The function leverages std::ifstream to open the file in binary mode and read its contents up to the end using ate mode. Finally, it retrieves the current position in the file using tellg(), which represents the file size in bytes.

Here's an illustration of the filesize function:

#include <fstream>

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

However, it's important to note that this method may not always yield accurate results, particularly with certain file systems. For a more reliable solution, consider alternative approaches such as using the stat() or _stat() functions.

The above is the detailed content of How can I efficiently determine the size of a file in C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template