几天发了这篇《用fstream对二进制文件的读写》,有朋友指出了VS2005的fstream对于中文路径支持不好的bug。我想大概是因为VS2005更加重视了对字符串的全球化支持,所以鼓励我们使用unicode编码的字符串,对于MBCS之类的支持可能就疏忽了吧。
我搜索了一下这个问题的解决,参考了如下资料写了演示代码。
fstream 和 中文路径 c++博客
About unicode settings in visual studio 2005, it really puzzled me a lot ms forum
MSDN
我综合了以上的内容,总结了3种方法,能够较好解决大家的困扰,包括可能无法使用cout的问题。
1: /******************************************************************** 2: created: 2008/05/10 3: created: 10:5:2008 23:56 4: filename: k:/sj/fstreamTest/fstreamTest/main.cpp 5: file path: k:/sj/fstreamTest/fstreamTest 6: file base: main 7: file ext: cpp 8: author: Gohan 9: *********************************************************************/ 10: #include <tchar.h> 11: #include <fstream> 12: #include <iostream> 13: using namespace std; 14: int main() 15: { 16: /************************************************************************/ 17: /* 方法1,使用_TEXT()宏定义将字符串常量指定为TCHAR*类型 */ 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: }
补充一下,第一种方法,如果不是静态字符串当作路径的话,记得传入TCHAR*类型字符串作为路径,应该就没问题了。
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/fengzhijiaxu/archive/2009/11/18/4829229.aspx