首页 > 解决方案 > 如何在c ++ ofstream中打开包含日语单词的文件路径?

问题描述

我正在使用 c++ 中的 ofstream 编写输出文件,文件路径是 c:\my_folder\フォルダ\text_file.txt

但它显示找不到路径,这是我的代码(我在 Visual Studio 2017 社区版中尝试过)

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    ofstream outfile;
    outfile.open(c:\\my_folder\\フォルダ\\text_file.txt,ios::out);
    if(!outfile)
     {
        cout<<"Path not found\n";    
     }
     outfile << "Hello world\n";
     outfile.close();
     return 0;
}

我试过这样也参考 - Displaying Japanese characters in visual c++

#include <string>
#include <iostream>

#include <windows.h>

int main()
{
    int codepage = CP_ACP; //CP_ACP, CP_OEMCP
    int conv_codepage = CP_UTF8; //CP_UTF8
    char str[256];
    char str1[256];
    wchar_t tstr[256], tstr2[256];

    memset(str, 0x00, 256);
    memset(str1, 0x00, 256);
    memset(tstr, 0x00, 256);
    memset(tstr2, 0x00, 256);

    memcpy(str, "c:\\my_folder\\フォルダ\\text_file.txt", sizeof(str));

    int nLen = MultiByteToWideChar(codepage, 0, str, -1, 0, 0); 
    MultiByteToWideChar(codepage, 0, str, -1, tstr, nLen);

    int len = WideCharToMultiByte( conv_codepage, 0, tstr, -1, NULL, 0, 0, 0 ); 
    WideCharToMultiByte(conv_codepage, 0, tstr, -1, str1, len ,0 ,0);

    cout << "2... " << str1 << endl;

   ofstream outfile;
     outfile.open(str1,ios::out);

    if(!outfile)
     {
        cout<<"Path not found\n";    
     }
     outfile << "Hello world\n";
     outfile.close();
     return 0;   
}

我也尝试过使用 wchar_t 但它们都不起作用,

std::wcout.imbue(std::locale("ja_jp.utf-8"));
    wchar_t c_name = L"c:\\my_folder\\フォルダ\\text_file.txt";
    wofstream outfile;
        outfile.open(c_name,ios::out );

    if(!outfile)
     {
        cout<<"Path not found\n";    
     }
     outfile << "Hello world\n";
     outfile.close();

请帮我。

标签: c++c++11visual-c++

解决方案


推荐阅读