Posted on 2015-04-14 19:47 
eryar 阅读(3501) 
评论(0)  编辑 收藏 引用  所属分类: 
6.Others 
			 
			
		 
		std::fstream 中文路径
 eryar@163.com 
用C++来开发管道出图程序IsoAlgo时,当PCF文件名中包含中文时,读取文件会失败。将下面数据存成一个简单文件:中文.txt  放到目标目录中来测试: 
 
 
Figure 1 包含中文的文件 
简单测试程序代码如下所示: 
#include <fstream>
#include <cassert>
#include <iostream>
int main(int argc, char* argv[])
{
    std::ifstream aFile(argv[1]);
    assert(aFile.good());
    std::cout << aFile.rdbuf() << std::endl;
    return 0;
}
并在Visual Studio的命令参数中传进去文件名: 
 
 
Figure 2 Set Command Arguments 
运行程序,会得到如下错误提示窗口: 
 
 
Figure 3 assert for the file 
这是加上断言assert的效果,在Debug模式下可以很快定位到错误,而在Release模式下就把这一行代码忽略了。 
在网上搜了下std::ifstream读取中文文件名的文件的解决方案: 
v 使用C语言的函数设置成中文运行环境: 
setlocale(LC_ALL,"Chinese-simplified"); 
v 使用STL中的函数设置为系统语言环境: 
std::locale::global(std::locale("")); 
因为IsoAlgo使用了STL的C++,所以选择方案2。实现代码如下所示: 
#include <fstream>
#include <cassert>
#include <iostream>
int main(int argc, char* argv[])
{
    std::locale::global(std::locale(""));
    std::ifstream aFile(argv[1]);
    std::locale::global(std::locale("C"));
    assert(aFile.good());
    std::cout << aFile.rdbuf() << std::endl;
    return 0;
}
程序运行结果如下图所示: 
