我怎样才能读取wfstream二进制数据? [英] How can I read binary data from wfstream?
问题描述
我有一个小问题,从文件中读取数据。我希望能够读取wstring的年代,作为藏汉(大小是以字节为单位)任意大小的原始数据块。
I have a slight problem reading data from file. I want to be able to read wstring's, aswell as a chunk of raw data of arbitrary size (size is in bytes).
std::wfstream stream(file.c_str());
std::wstring comType;
stream >> comType;
int comSize;
stream >> comSize;
char *comData = new char[comSize];
memset(comData, 0, comSize);
stream.read(comData, comSize);
//error C2664 : 'std::basic_istream<_Elem,_Traits>::read'
// : cannot convert parameter 1 from 'char *' to 'wchar_t *'
也许我错了使用流或类似的规定。基本上,我想读一个wstring的,数据的大小,随后(可能是任何数量的字节),接着成分数据的许多字节。很明显,因为模板假定wchar_t的的我无法读取字符的。
Perhaps I am using wrong streams, or something along those lines. Basically, I want to read a wstring, size of the data followed (which could be any number of bytes), followed by that many bytes of component data. Obviously, I can't read char's because the template assumes wchar_t's.
我可以读取wchar_t的的但我必须确保数据存储的sizeof由(wchar_t的)作为对齐。否则,我可能最终会破坏流。当数据为15字节的情况是。我将不得不读16字节,然后掩蔽不需要的字节,寻求流以15个字节的偏移量(如果可能的话与wchar_t的模板?),以便能够读出下一个数据块。
I can read wchar_t's but then I have to make sure the data is stored as aligned by sizeof(wchar_t). Otherwise, I could end up corrupting the stream. A scenario would be when the data is 15 bytes. I would have to read 16 bytes, then mask the unwanted byte, seek the stream to 15 bytes offset (if possible with wchar_t templated?) to be able to read the next data chunk.
显然,应的是实现什么,我试图做的更好的方式。
Clearly, there should be a nicer way of achieving what I am trying to do.
推荐答案
与stream.read的问题是,它使用的wchar_t为字符单位与wfstream。如果你使用的fstream它使用char作为字符单位。
the problem with the stream.read is that it uses wchar_t as "character unit" with wfstream. If you use fstream it uses char as "character unit".
如果你想阅读宽字符这将工作:
This would work if you want to read wide characters:
wchar_t *comData = new wchar_t[comSize];
stream.read(comData, comSize);
另外15字节的数据不能与广泛流中读取,因为最小单位是至少2个字节(见下文),所以你只能读sizwof(wchar_t的)大块* N
Also 15 bytes of data can't be read with a wide stream, because the smallest unit is at least 2bytes (see below), so you can only read chunks of sizwof(wchar_t) * n.
但是,如果您关心应用wfstream的便携/ wchar_t的是,也许不是最好的解决方案,因为没有标准有多宽wchar_t为(例如在Windows wchar_t的是16bit许多UNIX / Linux系统是32位)。
But if you are concerned about portability of the application wfstream/wchar_t is maybe not the best solution because there is no standard how wide wchar_t is (e.g. on windows wchar_t is 16bit on many unix/linux systems it is 32bit).
与存储文本为宽字符的第二个问题是字节顺序,我会建议使用UTF-8文本存储。
The second problem with storing text as wide characters is endianess, i would suggest to use UTF-8 for text storage.
这篇关于我怎样才能读取wfstream二进制数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!