获取文件夹的大小

时间:2016-04-28 21:07:23

标签: c++ file size

我在视觉工作室2015上工作,在Windows上。是否有可能从此代码中的路径获取每个文件或文件夹的大小: 我需要获得像int一样的大小,千字节数

vector<string>listDirectories(const char *path) {
    DIR *dir = opendir(path);

    vector<string> directories;

    struct dirent *entry = readdir(dir);

    while (entry != NULL)
    {
        if (entry->d_type == DT_DIR)
            directories.push_back(entry->d_name);

        entry = readdir(dir);
    }

    closedir(dir);
    return directories;


}

1 个答案:

答案 0 :(得分:1)

使用新的<filesystem>标题,您确实可以,#include <experimental/filesystem>(实验性的,因为它是C ++ 17的功能 - 但这很好,因为您声明您正在使用VS2015,因此它可以使用并查看以下内容以满足您的需求:

http://en.cppreference.com/w/cpp/experimental/fs/file_size

std::experimental::filesystem::file_size以整数个字节返回路径给出的文件大小,请注意,此path不是const char*std::string路径,而是fs::path作为文件系统标题的一部分。

假设问题中的函数返回目录中的文件列表,您可以(未经测试)打印给定目录中的每个文件大小:

#include <iostream>
#include <fstream>
#include <experimental/filesystem>
#include <vector>

namespace fs = std::experimental::filesystem;

//...

int main(void) {
    std::vector<std::string> file_names_vec = listDirectories("dir");

    size_t folder_size = 0;
    for (auto it = file_names_vec.begin(); it != file_names_vec.end(); ++it) {
         fs::path p = *it;
         std::cout << "Size of file: " << *it << " = " << fs::file_size(p) << " bytes";
         folder_size += fs::file_size(p);
    }
}
相关问题