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

问题描述 投票:1回答:1

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

我该怎么办?

c++11 unicode filesystems boost-filesystem
1个回答
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;
}
© www.soinside.com 2019 - 2024. All rights reserved.