中文路径使用有问题的原因:
使用ofstream在桌面创建一个中文名称的文本文件,例如“你好.txt”:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    char* x = wchar2char(L"C:\\users\\arcueidbrunestud\\desktop\\你好.txt");
    ofstream ofs(x);
    if (ofs.is_open()) printf("true\n");
    else printf("false\n");
    return 0;
}运行的结果自然是true,可以创建中文名称的文本文件:
 
      但是,在桌面上查看文本文件的时候,发现文件名称是乱码:
 
      
     
      方法1:windows下,无需第三方库
     
    
使用头文件:
#include <iostream>
#include <fstream>
#include <windows.h>
using namespace std;首先定义把wchar转char的函数:
char* wchar2char(const wchar_t* wchar)
{
    char* m_char;
    int len = WideCharToMultiByte(CP_ACP, 0, wchar, -1, NULL, 0, NULL, NULL);
    m_char = new char[len + 1];
    WideCharToMultiByte(CP_ACP, 0, wchar, -1, m_char, len, NULL, NULL);
    m_char[len] = '\0';
    return m_char;
}
     进行读写包含中文路径的操作时,使用如下格式(
     
      注意字符串前的L
     
     ):
    
int main(){  
    char* x = wchar2char(L"C:\\users\\arcueidbrunestud\\desktop\\你好.txt");
    ofstream ofs(x);
    if (ofs.is_open()) printf("true\n");
    else printf("false\n");
    return 0;
}运行结果:
 
      
     
      方法2:使用Qt
     
    
引入头文件:
#include <iostream>
#include <fstream>
#include <QtCore/qtextcodec.h>
using namespace std;
     进行读写包含中文路径的操作时,使用如下格式(
     
      注意字符串前的L
     
     ):
    
int main(){  
    QTextCodec* codec = QTextCodec::codecForName("gbk");
    string x = codec->fromUnicode(L"C:\\users\\arcueidbrunestud\\desktop\\你好.txt").toStdString();
    ofstream ofs(x);
    if (ofs.is_open()) printf("true\n");
    else printf("false\n");
    return 0;
}
 
版权声明:本文为m0_61800313原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
