Error with character mapping when conversing filesystem::path to string or printing them with MSVC

76 Views Asked by At

I'm using VS2022 and wrote the following program:

void rena::HUFO::_traversal_dir_write_to_hlist( const std::filesystem::path& dir ){
    for ( auto it : std::filesystem::directory_iterator( dir ) )
    {
        auto fp = it.path(); // file path
        if ( std::filesystem::is_directory( fp ) )
        {
            _traversal_dir_write_to_hlist( fp );
        } // dir found, traversal it
        else
        {
            if ( fp == this -> _hufopath )
            {
                continue;
            } // ignore HUFO itself
            DEBUG_MSG( fp );
            HASHOBJ temp;
            temp.fp = std::filesystem::relative( fp , this -> _pdpath );
            this -> _hlist.push_back( temp );
        } // write relative path to _hlist
    }
    return;
}

It works perfectly until I reached a file which its name is FM_(`・ω・´)シャキーン1(1秒).ogg, the program called abort in runtime.

I caught the exception and it is There are no characters to which this Unicode character can be mapped in the multibyte target code page. (I guess because I use Chinese version and the original message was 在多字节的目标代码页中,没有此 Unicode 字符可以映射到的字符.) Same exception was caught when I tried to do fp.string().

And I also found out that this exception was caught only when I tried to print this filename. When I deleted this DEBUG_MSG( fp );, nothing happened, no exception was caught.

I tried to use wcout and wstring, but they didn't solve my problem. No more exception was caught, but the output was broken.

The output was (with cout and `string and exception catch):

"...\\camera.wav"
Error occured when traversaling directory "...":
在多字节的目标代码页中,没有此 Unicode 字符可以映射到的字符。
Error path output unavaliable.
Skip the current file.
"...\\FM_アイテムゲット11(1秒).ogg"
"...\\FM_アイテムゲット2(1秒).ogg"
"...\\FM_アイテムゲット3(1秒).ogg"
... (other files)

And with wcout and wstring it was like:

"...\\camera.wav"
"...\\FM_(

I also tried to use .u8string(), but the output was also full of mojibakes.

I would like to know (if anyboby knows) why this happened and how I can solve it, print the path successfully and with no nonsense.

0

There are 0 best solutions below