获取文件夹的大小 [英] Getting the size of a folder

查看:268
本文介绍了获取文件夹的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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;


}


推荐答案

使用新的< filesystem> 头你真的可以, #include< experimental / filesystem> 实验,因为它是一个C ++ 17功能 - 但这是很好,因为你声明你正在使用VS2015,所以它可以使用),并检查下面来做你需要的:

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 请注意,这个路径不是一个 const char * 或以整数字节给出的文件 std :: string path,而是将 fs :: path 作为文件系统头文件的一部分。

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

这篇关于获取文件夹的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆