我尝试从此文件中读取1个随机项:
//"file.bin" structure:
Offset Length
0 4 Total items (=n)
4 4 Item 1 Position = 4 + n * 5 = offset1
8 1 Item 1 Length = l1
9 4 Item 2 Position = offset2 = offset1 + l1
13 1 Item 2 Length
14 4 Item 3 Position
18 1 Item 3 Length
...
4+n*5 l1 Item 1
4+n*5+l1 l2 Item 2
...
但是我得到了错误:nbg
我得到的字符串不完全在文件中。我已经成功尝试了C#代码,但是我是C ++的新手,我不知道是什么导致了错误。
下面的代码有什么问题?
FILE* f;
if (!fopen_s(&f, "D:\\file.bin", "rb"))
{
byte* buf = new byte[4];
byte length;
char* sss;
unsigned int number;
// Read Total Items Number
fread(buf, sizeof(byte), 4, f);
number = int_from_bytes(buf, true);
//Generate random number
std::random_device rd;
std::mt19937 rng(rd());
std::uniform_int_distribution<int> uni(0, number);
auto random_integer = uni(rng);
// Seek to read Random item Position-Length
// Read Post
fseek(f, 4 + 5 * random_integer, SEEK_SET);
fread(buf, sizeof(byte), 4, f);
number = int_from_bytes(buf, true);
// Read Length
fread(&length, sizeof(byte), 1, f);
int len = static_cast<byte>(length);
// Read String
fseek(f, number, SEEK_SET);
sss = new char[len + 1];
fread(sss, 1, len, f);
const wchar_t* nbg = toWideChar(sss);
MessageBoxW(NULL, nbg, L"", 0);
delete[] buf;
delete[] sss;
fclose(f);
}
wchar_t* toWideChar(const char* input)
{
int wchars_num2 = MultiByteToWideChar(CP_UTF8, 0, input, -1, NULL, 0);
wchar_t* wstr2 = new wchar_t[wchars_num2];
MultiByteToWideChar(CP_UTF8, 0, input, -1, wstr2, wchars_num2);
return wstr2;
}
int int_from_bytes(const byte * bytes, _Bool reverse)
{
int tmp;
if (reverse)
{
for (size_t i = sizeof(tmp); i--; ++bytes)
((char *)&tmp)[i] = *bytes;
}
else memcpy(&tmp, bytes, sizeof(tmp));
return tmp;
}
问题描述中的细节很少,因此我在这里猜测,但可能是问题出在sss
缓冲区末尾缺少NUL终止符。在调用之前添加以下行toWideChar(sss)
:
sss[len] = '\0';
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句