让VS2005中的fstream支持中文路径文件打开

来源:互联网 发布:ansys cfd 仿真软件 编辑:程序博客网 时间:2024/05/17 08:41

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*类型字符串作为路径,应该就没问题了。image
原创粉丝点击