首頁  >  文章  >  後端開發  >  如何有效地確定 C 中檔案的大小?

如何有效地確定 C 中檔案的大小?

Patricia Arquette
Patricia Arquette原創
2024-11-15 14:06:03278瀏覽

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(); 
}

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.

以上是如何有效地確定 C 中檔案的大小?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn