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

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

Patricia Arquette
發布: 2024-11-15 14:06:03
原創
350 人瀏覽過

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中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板