解决fstream不能打开带有中文路径文件的问题

方法1:使用_TEXT()宏定义将字符串常量指定为TCHAR*类型
方法2:使用STL中的locale类的静态方法指定全局locale,静态函数locale::global(newloc)可设置newloc为全局locale,并且返回以前的全局locale,可将之保存起来以后恢复,如果使用localeloc=locale::global(locale(""))设置全局locale后没有用locale::global(loc)恢复的话,那么在程序后面的cout语句就不能输出中文了,虽然这时候操作中文文件没有问题,但是这也是很容易让人掉入陷阱的地方,应该值得注意

fstream file;
file.open(_TEXT("c://测试//测试文本.txt"));
cout<<file.rdbuf();
file.close();

fstream file;
locale::global(locale(""));
file.open("c://测试//测试文本.txt");
locale::global(locale("C"));
cout<<file.rdbuf();
file.close();
 
fstream file;
localeloc=locale::global(locale(""));
file.open("c://测试//测试文本.txt");
ocale::global(loc);
cout<<file.rdbuf();
file.close();

 

posted @ 2011-03-29 23:29  Leung文  阅读(402)  评论(0编辑  收藏  举报