【问题标题】:Get the size of the directory having unicode filenames in c++在 c++ 中获取具有 unicode 文件名的目录的大小
【发布时间】:2017-12-22 12:09:01
【问题描述】:

我想计算一个目录的大小(以字节为单位),这是我使用 boost::filesystem 的算法

#include <boost/filesystem.hpp>
#include <string>
#include <functional>

using namespace boost::filesystem;
using namespace std;

// this will go through the directories and sub directories and when any
// file is detected it call the 'handler' function with the file path
void iterate_files_in_directory(const path& directory,
                                     function<void(const path&)> handler)
{
    if(exists(directory))
        if(is_directory(directory)){
            directory_iterator itr(directory);
            for(directory_entry& e: itr){
                if (is_regular_file(e.path())){
                    handler(e.path().string());
                }else if (is_directory(e.path())){
                    iterate_files_in_directory(e.path(),handler);
                }
            }
        }
}

uint64_t get_directory_size(const path& directory){
    uint64_t size = 0;
    iterate_files_in_directory(directory,[&size](const path& file){
        size += file_size(file);
    });
    return size;
}

当目录包含具有简单文件名的文件(即没有任何 Unicode 字符)时,它可以正常工作,但是当发现任何具有 Unicode 字符的文件时,它会引发异常:

什么():

boost::filesystem::file_size: The filename, directory name, or volume label syntax is incorrect

我该怎么办?

【问题讨论】:

  • 我不知道您是否见过this tutorial,但我认为您需要以某种方式明确使用std::wstring 才能使其工作?我没试过,那可能是完全错误的......
  • 尝试在此处删除.string()handler(e.path().string());

标签: c++11 unicode filesystems boost-filesystem


【解决方案1】:

我已经解决了我的问题。我在handler(e.path().string()) 中删除了.string(),这就是我的新代码

#include <boost/filesystem.hpp>
#include <string>
#include <functional>

using namespace boost::filesystem;
using namespace std;

// this will go through the directories and sub directories and when any
// file is detected it call the 'handler' function with the file path
void iterate_files_in_directory(const path& directory,
                                     function<void(const path&)> handler)
{
    if(exists(directory))
        if(is_directory(directory)){
            directory_iterator itr(directory);
            for(directory_entry& e: itr){
                if (is_regular_file(e.path())){
                    handler(e.path()); // here was the bug in the previous code
                }else if (is_directory(e.path())){
                    iterate_files_in_directory(e.path(),handler);
                }
            }
        }
}

uint64_t get_directory_size(const path& directory){
    uint64_t size = 0;
    iterate_files_in_directory(directory,[&size](const path& file){
        size += file_size(file);
    });
    return size;
}

【讨论】:

    猜你喜欢
    • 2010-11-10
    • 1970-01-01
    • 2013-04-01
    • 2013-05-26
    • 2011-07-18
    • 2010-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多