有时候用ifstream 或ofstream 打开带有中文路径的文件会失败。
解决办法:
1
、使用C
语言的函数设置为中文运行环境
setlocale(LC_ALL,"Chinese-simplified");
2
、使用STL
函数设置为系统语言环境
std::locale::global(std::locale(""));
当然选2 啦!
ofstream writefile;
string
filename=("d:/
我的文档/
测试.txt");
locale loc = locale::global(locale("")); //
要打开的文件路径含中文,设置全局locale
为本地环境
writefile.open(filename.c_str(),ios::out); //
打开文件
locale::global(loc);//
恢复全局locale
用locale 对象的name 方法可以看到,通过locale("") 构造出的locale 对象的name 为"Chinese_People's Republic of China.936" ,而原始的locale 对象的name 为"C" ,也就是缺省的ANSI _C 公约。
注意:如果使用locale loc = locale::global(locale("")) 设置全局locale 后没有用 locale::global(loc) 恢复的话,那么在程序后面的cout 语句就不能输出中文了,虽然这时候操作中文文件没有问题,但是这也是很容易让人掉入陷阱的地方,应该值得注意。解决方法:
先将CString 转为char*
CString str=view->m_sFilePath;
//CString str = "";
//ofstream
中传的参数不能有汉字,必须转换一下是其暂缓方法
str.AppendFormat("cluster%d%d.txt",aMatrix->X_part,aMatrix->Y_part);
char* sz =
str.GetBuffer(str.GetLength());
locale loc = locale::global(locale(""));
ofstream ofile(sz);
转载网友方法:
/*
方法1
,使用_TEXT()
宏定义将字符串常量指定为TCHAR*
类型 这种情况下必须是unicode
下编译 */
18: /*
如果是我,首选此类型
*/
19:
/************************************************************************/
20: fstream file;
21: file.open(_TEXT("c://
测试//
测试文本.txt"));
22: cout<<file.rdbuf();
23: file.close();
24:
25:
/************************************************************************/
26: /*
方法2
,使用STL
中的locale
类的静态方法指定全局locale
*/
27: /*
使用该方法以后,cout
可能不能正常输出中文,十分蹊跷 */
28: /*
我发现了勉强解决的方法:不要在还原区域设定前用cout
或wcout
输出中文
*/
29: /*
否则后果就是还原区域设定后无法使用cout wcout
输出中文
*/
30:
/************************************************************************/
31: locale::global(locale(""));//
将全局区域设为操作系统默认区域
32: file.open("c://
测试//
测试文本2.txt");//
可以顺利打开文件了
33:
locale::global(locale("C"));//
还原全局区域设定
34: cout<<file.rdbuf();
35: file.close();
36:
37:
/************************************************************************/
38: /*
方法3
,使用C
函数setlocale
,不能用cout
输出中文的问题解决方法同上 */
39:
/************************************************************************/
40:
setlocale(LC_ALL,"Chinese-simplified");//
设置中文环境
41: file.open("c://
测试//
测试文本3.txt");//
可以顺利打开文件了
42: setlocale(LC_ALL,"C");//
还原
43: cout<<file.rdbuf();
44: file.close();
45: }
本文介绍了解决在C++中使用ifstream和ofstream打开含有中文路径文件的问题。提供了多种解决方案,包括使用setlocale和locale::global来设置中文运行环境,并详细说明了每种方法的注意事项。

被折叠的 条评论
为什么被折叠?



