Posted on 2015-04-14 19:47
eryar 閱讀(3482)
評(píng)論(0) 編輯 收藏 引用 所屬分類:
6.Others
std::fstream 中文路徑
eryar@163.com
用C++來開發(fā)管道出圖程序IsoAlgo時(shí),當(dāng)PCF文件名中包含中文時(shí),讀取文件會(huì)失敗。將下面數(shù)據(jù)存成一個(gè)簡(jiǎn)單文件:中文.txt 放到目標(biāo)目錄中來測(cè)試:
Figure 1 包含中文的文件
簡(jiǎn)單測(cè)試程序代碼如下所示:
#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的命令參數(shù)中傳進(jìn)去文件名:
Figure 2 Set Command Arguments
運(yùn)行程序,會(huì)得到如下錯(cuò)誤提示窗口:
Figure 3 assert for the file
這是加上斷言assert的效果,在Debug模式下可以很快定位到錯(cuò)誤,而在Release模式下就把這一行代碼忽略了。
在網(wǎng)上搜了下std::ifstream讀取中文文件名的文件的解決方案:
v 使用C語言的函數(shù)設(shè)置成中文運(yùn)行環(huán)境:
setlocale(LC_ALL,"Chinese-simplified");
v 使用STL中的函數(shù)設(shè)置為系統(tǒng)語言環(huán)境:
std::locale::global(std::locale(""));
因?yàn)镮soAlgo使用了STL的C++,所以選擇方案2。實(shí)現(xiàn)代碼如下所示:
#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;
}
程序運(yùn)行結(jié)果如下圖所示: