在 C++ 中使用 fread 从二进制文件中读取字符串及其长度

Read string and its length from binary file using fread in C++

Bellow 你可以找到一个代码片段,我曾经用它写一个 string_length 到二进制文件,但代码没有按预期工作。写入后,我打开了输出文件,字符串就在那里,但是当我从文件中读取字符串时,它只读取了部分字符串。似乎在读取 string_length 后,文件指针查找的内容超出了应有的范围,然后它错过了字符串的前 8 个字符!

#include <iostream>
#include <string>

FILE* file = nullptr;

bool open(std::string mode)
{
    errno_t err = fopen_s(&file, "test.code", mode.c_str());
    if (err == 0) return true;
    return false;
}

void close()
{
    std::fflush(file);
    std::fclose(file);
    file = nullptr;
}

int main()
{
    open("wb"); // open file in write binary mode

    std::string str = "blablaablablaa";

    auto sz = str.size();
    fwrite(&sz, sizeof sz, 1, file); // first write size of string
    fwrite(str.c_str(), sizeof(char), sz, file); // second write the string

    close(); // flush the file and close it

    open("rb"); // open file in read binary mode

    std::string retrived_str = "";

    sz = -1;
    fread(&sz, sizeof(size_t), 1, file); // it has the right value (i.e 14) but it seems it seeks 8 bytes more!
    retrived_str.resize(sz);
    fread(&retrived_str, sizeof(char), sz, file); // it missed the first 8 char

    close(); // flush the file and close it

    std::cout << retrived_str << std::endl;

    return 0;
}

PS:我删除了代码中的检查以使其更具可读性。

您正在用文件内容破坏 retrieved_str 对象,而不是将文件内容读入由 retrieved_str 控制的缓冲区。

fread(&retrived_str[0], 1, sz, file);

或者,如果您使用 C++17 及其 non-const std::string::data 方法:

fread(retrived_str.data(), 1, sz, file);

改变

fread(&retrived_str, sizeof(char), sz, file); // it missed the first 8 char

fread((void*)( retrived_str.data()), sizeof(char), sz, file); // set the data rather than the object