在C ++中使用ifstream读取多字节字符 [英] Reading Multi byte characters using ifstream in C++

查看:201
本文介绍了在C ++中使用ifstream读取多字节字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我正在读一个包含日文字符的.csv文件。

我使用ifstream来解析文件getline()读取给定文件中的每一行。



由于文件包含日文字符,因此文件格式为多字节字符集(MBCS)。

所以它在文件的开头附加3个特殊字符,其中一个是标题,表示文件格式是MBCS。



现在怎么样我可以通过确保我不应该阅读这3个特殊字符来阅读这个具有日文字符的文件。



到目前为止我正在使用这个..... br />


Hi,

I am reading a .csv file which contains Japanese characters.
I am using ifstream to parse the file and getline() to read each line in the given file.

As the file contains Japanese characters so file format is Multibyte character set (MBCS).
So it appends 3 special characters at the begining of the file, out of which one is the header to denote that the file format is MBCS.

Now how can i read this file having Japanese character by making sure that i should not read those 3 special characters..

so far i am using this .....

TCHAR *filename = "F:\\GPDM.csv";
	
	wstring temp;

	wifstream fstr;

	fstr.open(filename, ios::in);

	if (fstr.fail())
	{
		std::cout<<"File Open Error\n";
	}
	else
	{
		std::cout<<"File Open Success\n";
	}

	getline(fstr, temp);







这里temp仍然包含那3个特殊字符......



请帮帮我。




Here "temp" still contains those 3 special characters...

Please help me out in this.

推荐答案

您应该根据 BOM [ 解析文件的第一个字符href =http://en.wikipedia.org/wiki/Byte_order_marktarget =_ blanktitle =New Window> ^ ]规则并采取相应的行动。
You should parse the first characters of the file according to BOM[^] rules and act appropriately.


假设您已经打开了一个文件:



Assuming you have an open file already:

char a, b, c;
f.Read(&a, 1);
f.Read(&b, 1);
f.Read(&c, 1);

if (a == (char)0xEF && b==(char)0xBB && c==(char)0xBF)
    f.Seek(3, CFile::begin);



...



做你的下一步行动(比如Read或ResdString或者排序)。

当然你总是可以将上面的代码翻译成任何使用文件套件的方式。



也许有点脏,但对我有用。


...

Do your next move (like Read or ResdString or of the sort).
Of course you can always translate the code above to whatever way of using files suites you.

Maybe a little dirty, but works for me.


这篇关于在C ++中使用ifstream读取多字节字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆