Sta*_*ent 5 c++ binary stl stream
我从文件中读取数据时遇到了一些问题.我希望能够读取wstring,以及任意大小的原始数据块(大小以字节为单位).
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 *'
Run Code Online (Sandbox Code Playgroud)
也许我正在使用错误的流,或类似的东西.基本上,我想读取一个wstring,跟随的数据大小(可以是任意数量的字节),然后是那么多字节的组件数据.显然,我无法读取char,因为模板假定为wchar_t.
我可以读取wchar_t,但是我必须确保数据存储为sizeof(wchar_t)对齐.否则,我最终可能会破坏流.一种情况是数据是15个字节.我必须读取16个字节,然后屏蔽不需要的字节,寻找流到15个字节的偏移量(如果可能,使用wchar_t模板化?)以便能够读取下一个数据块.
显然,应该有一种更好的方式来实现我想要做的事情.
考虑到您的要求,我认为 wfstream 不是正确的选择。考虑使用类似以下代码片段的内容。
#include "stdafx.h"
#include <fstream>
#include <iostream>
int _tmain(int argc, _TCHAR* argv[])
{
std::wstring str(L"hello");
size_t size1 = str.length();
char data[] = { 0x10, 0x20, 0x30 };
size_t size2 = 3;
FILE* output = NULL;
if (_wfopen_s(&output, L"c:\\test.bin", L"wb") == 0) {
fwrite(&size1, sizeof(size_t), 1, output);
fwrite(str.c_str(), size1 * sizeof(wchar_t), 1, output);
fwrite(&size2, sizeof(size_t), 1, output);
fwrite(data, size2, 1, output);
fclose(output);
}
FILE* input = NULL;
if (_wfopen_s(&input, L"c:\\test.bin", L"rb") == 0) {
fread(&size1, sizeof(size_t), 1, input);
wchar_t* wstr = new wchar_t[size1 + 1];
fread(wstr, size1 * sizeof(wchar_t), 1, input);
std::wstring str(wstr, size1);
delete[] wstr;
fread(&size2, sizeof(size_t), 1, input);
char* data1 = new char[size2];
fread(data1, size2, 1, input);
std::wcout << str.c_str() << std::endl;
for (size_t i = 0; i < size2; ++i) {
std::wcout << std::hex << "0x" << int(data1[i]) << std::endl;
}
delete[] data1;
fclose(input);
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这输出:
hello
0x10
0x20
0x30
Run Code Online (Sandbox Code Playgroud)