您的位置:首页 > 其它

fstream默认不支持中文路径和输出整数带逗号的解决办法

2010-08-10 21:09 489 查看
我们用fstream来创建一个新文件,如果文件路径中带有中文,则创建一般会失败。如下面代码:

]#include <iostream>
#include <fstream>
#include <string>
#include <direct.h>

using namespace std;

void main()
{
_mkdir("测试");      //新建一个中文文件夹
ofstream outfile( "测试/test.txt", ios::out );     //创建文件
if( !outfile )
{
cout << "Failed to create file!";
return ;
}
outfile.close();
}


程序将输出创建文件夹失败的信息。

一个解决办法是:在中文操作系统下,调用locale::global(std::locale("")),将全局区域设置为中文,如下例:

]#include <iostream>
#include <fstream>
#include <string>
#include <direct.h>

using namespace std;

void main()
{
locale::global(std::locale(""));     //将全局区域设为操作系统默认区域,以支持中文路径
_mkdir("测试");      //新建一个中文文件夹
ofstream outfile( "测试/test.txt", ios::out );     //创建文件
if( !outfile )
{
cout << "Failed to create file!";
return ;
}
int i = 123456789;
outfile << "i = " << i << "/n";   //输出带逗号
outfile.close();
setlocale( LC_ALL, "C" );     //恢复全局locale,如果不恢复,可能导致cout无法输出中文
}


创建文件成功,在程序的“测试”文件下出现个test.txt文件。需要注意的是最后需要调用setlocale( LC_ALL, "C" )还原,否则会出现未知错误。

此时我们发现,test.txt中的i值显示为123,456,789,出现了逗号。这是因为中文习惯问题。我们在读取文件的时候,读入i值时,可能读入一个值为123的整数,并不是我们希望的123456789,所以我们写文件时,希望不要写入逗号。一个办法是现将整数转换为字符串再进行输出,如:

]int i = 123456789;
char ch[20];
sprintf((char *)&ch, "%d", i);    //整数数据转换为字符数组。
outfile << "i = "  << ch << '/n';  //输出不带逗号


上述问题的解决方法有很多,大家可以试试。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: