在 C++ 中获取文件大小

本文将演示如何在 C++ 中获取文件大小的多种方法。

使用 std::filesystem::file_size 函数在 C++ 中获取文件大小

std::filesystem::file_size 是 C++ 文件系统库函数,用于检索文件的字节大小。std::filesystem::file_size 使用文件的路径作为函数参数,其类型为 std::filesystem::path。在下面的例子中,我们传递了文件路径的字符串值,然后用它来构造相应的对象并检索文件大小。

#include <iostream>#include <string>#include <fstream>#include <filesystem>using std::cout; using std::cin;
using std::endl; using std::ifstream;
int main() {
    string path = "input.txt";
    cout << "size of file '" << path << "' = " <<
            std::filesystem::file_size(path) << endl;
    return EXIT_SUCCESS;
}

输出:

size of file 'inbox.txt' = 10440

使用 std::filesystem::file_sizestd::filesystem::path 在 C++ 中获取文件大小

std::filesystem::file_size 函数的另一种用法是将文件路径值作为 path 类型变量插入。首先,你需要在使用类型之前包含 using std::filesystem::path 语句。接下来,我们可以声明 path 对象,如下面的示例代码所示,并用一个字符串文字来初始化它。构造的变量被传递给 file_size 函数以获取文件大小。

#include <iostream>#include <string>#include <fstream>#include <unistd.h>#include <sys/stat.h>#include <fcntl.h>#include <filesystem>using std::cout; using std::cin;
using std::endl; using std::ifstream;
using std::string; using std::filesystem::path;
using std::error_code;
int main() {
    class path fd_path = "input.txt";
    cout << "size of file '" << fd_path << "' = " <<
            std::filesystem::file_size(fd_path) << endl;
    return EXIT_SUCCESS;
}

输出:

size of file 'inbox.txt' = 10440

使用 std::filesystem::file_sizeerror_code 在 C++ 中获取文件大小

由于 std::filesystem::file_size 利用底层操作系统服务来检索文件的大小,所以很有可能会失败,引发一些异常。为了更好地处理每次 file_size 函数调用,建议使用 error_code 对象作为第二个参数,并存储失败时的错误信息。因此,我们可以评估 error_code 对象,并使用 if...else 语句实现错误处理代码。

#include <iostream>#include <string>#include <fstream>#include <filesystem>using std::cout; using std::cin;
using std::endl; using std::ifstream;
using std::string; using std::filesystem::path;
using std::error_code;
int main() {
    string path = "input.txt";
    error_code ec{};
    auto size = std::filesystem::file_size(path, ec);
    if (ec == error_code{})
        cout << "size of file '" << path << "' = " << size << endl;
    else
        cout << "Error accessing file '" << path
              << "' message: " << ec.message() << endl;
    return EXIT_SUCCESS;
}

输出:

size of file 'inbox.txt' = 10440

使用 stat 函数在 C++ 中获取文件大小

stat 是符合 POSIX 标准的函数,在多个操作系统中都可以使用。它通常是 std::filesystem::file_size 方法下面的函数。stat 以字符串作为第一个参数,表示 struct stat 类型对象的文件地址的路径作为第二个参数。

struct stat 是一个特殊的预定义对象,在 stat 函数调用成功后,存储多个文件参数。需要注意的是,我们只需要访问 struct stat 对象中的 st_size 数据成员,它以字节数的形式存储文件大小。

#include <iostream>#include <string>#include <unistd.h>#include <sys/stat.h>#include <fcntl.h>using std::cout; using std::cin;
using std::endl; using std::ifstream;
using std::string;
int main() {
    string path = "input.txt";
    struct stat sb{};
    if (!stat(path.c_str(), &sb)) {
        cout << "size of file '" << path << "' = "
                << sb.st_size << endl;
    } else {
        perror("stat");
    }
    return EXIT_SUCCESS;
}

输出:

size of file 'inbox.txt' = 10440