Getting the size of a folder

2019-09-16 15:29发布

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;


}

标签: c++ file size
1条回答
ら.Afraid
2楼-- · 2019-09-16 15:57

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);
    }
}
查看更多
登录 后发表回答