获取c ++中具有unicode文件名的目录的大小

时间:2017-12-22 12:09:01

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

我想计算目录的大小(以字节为单位),这是我的算法使用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

我该怎么办?

1 个答案:

答案 0 :(得分:0)

我已经解决了我的问题。我在.string()中删除了handler(e.path().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;
}