Getting the size of a folder

孤街醉人 提交于 2019-12-25 01:15:23

问题


I am working in visual studio 2015, on windows. Is there any possibility to get the size of each file or folder from a path in this code: I need to obtain size like a int, number of kilobytes

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:


With the new <filesystem> header you indeed can, just #include <experimental/filesystem>(experimental as it is a C++17 feature - but this is fine as you state you are using VS2015 so it's available to use) and check out the following to do what you need:

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

std::experimental::filesystem::file_size returns the size of the file given by the path in an integral number of bytes, note that this path is not a const char* or std::string path but rather a fs::path as part of the filesystem header.

Assuming the function in the question returns a list of files in a directory, you could do (untested) to print each file size in the given directory:

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


来源:https://stackoverflow.com/questions/36925472/getting-the-size-of-a-folder

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!