vc中ifstream ofstream不能读取带有中文路径的解决办法

有时候用ifstreamofstream打开带有中文路径的文件会失败。 

解决办法: 
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); 

[转]vc中ifstream ofstream不能读取带有中文路径 - Never give up! - ITeye博客
转载网友方法:

  1.   /* 方法1,使用_TEXT()宏定义将字符串常量指定为TCHAR*类型 这种情况下必须是unicode下  编译                */  
  2.   /* 如果是我,首选此类型                                                 */  
  3.   /************************************************************************/  
  4.   fstream file;   
  5.   file.open(_TEXT("c:\\测试\\测试文本.txt"));   
  6.   cout<<file.rdbuf();   
  7.   file.close();   
  8.   
  9.   /************************************************************************/  
  10.   /* 方法2,使用STL中的locale类的静态方法指定全局locale                   */  
  11.   /* 使用该方法以后,cout可能不能正常输出中文,十分蹊跷                    */  
  12.   /* 我发现了勉强解决的方法:不要在还原区域设定前用cout或wcout 输出中文   */  
  13.   /* 否则后果就是还原区域设定后无法使用cout wcout输出中文                 */  
  14.   /************************************************************************/  
  15.   locale::global(locale(""));//将全局区域设为操作系统默认区域   
  16.   file.open("c:\\测试\\测试文本2.txt");//可以顺利打开文件了   
  17.   locale::global(locale("C"));//还原全局区域设定   
  18.   cout<<file.rdbuf();   
  19.   file.close();   
  20.   
  21.   /************************************************************************/  
  22.   /* 方法3,使用C函数setlocale,不能用cout输出中文的问题解决方法同上      */  
  23.   /************************************************************************/  
  24.   setlocale(LC_ALL,"Chinese-simplified");//设置中文环境   
  25.   file.open("c:\\测试\\测试文本3.txt");//可以顺利打开文件了   
  26.   setlocale(LC_ALL,"C");//还原   
  27.   cout<<file.rdbuf();   
  28.   file.close();   
  29. }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值