gpt4 book ai didi

c++ - 从文件中读取随机字符串时出错

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:18:24 24 4
gpt4 key购买 nike

我试图从这个文件中读取 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
...

但我得到了错误:String 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';

关于c++ - 从文件中读取随机字符串时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30121975/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com