global locale と finename

Windows で名前に ASCII characters じゃない文字を使っている file を扱う場合、 global locale を system の locale にしてやらないと意図通りの名前にならないというハナシ。 ja_JP.UTF-8 な locale を使っている andLinux だと global locale が C だろうが system 固有 ( ja_JP.UTF-8 ) だろうがこの問題は発生しないのでとりあえず program の最初で設定してしまうというのがいいかも。

// main.cpp

#include <iostream>
#include <string>
#include <fstream>
#include <locale>

using namespace std;

void initialize_locale(void);

int main(const int argc, const char* const argv[]) {
    initialize_locale();

    if (argc < 2) {
        cerr << "Specify string." << endl;
        return 1;
    }

    string filename(argv[1]);
    filename.append(".txt");
    ofstream fout(filename.c_str(), ios::trunc);
    fout << argv[1] << endl;
    fout.close();

    return 0;
}

void initialize_locale(void) {
    const locale system_locale("");
    locale::global(system_locale);
    cin.imbue(system_locale);
    cout.imbue(system_locale);
    cerr.imbue(system_locale);
    wcin.imbue(system_locale);
    wcout.imbue(system_locale);
    wcerr.imbue(system_locale);
}

上記で initialize_locale() 関数中の locale::global(system_locale); てところがキモ。ここがないと化ける。