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

Error when reading a random string from a file

我试图从此文件中读取 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] = '[=10=]';