您的位置:首页 > 编程语言 > C语言/C++

C/C++中读取中文路径文件的方法

2011-11-07 11:17 495 查看
转自 http://apps.hi.baidu.com/share/detail/33007444

有时候用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: }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: