简体   繁体   中英

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

Bellow you can find a code snippet that I used to write an string_length with it to binary file but the code does not works as expected. After it writes I opened the output file and the string was located there but when I read the string from file it reads the string partially. It seems that after reading the string_length the file pointer seeks more than what it should and then it missed the first 8 characters of the string!

#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: I removed checks in the code in order to makes it more readable.

You're clobbering the retrieved_str object with the file contents rather than reading the file contents into the buffer controlled by retrieved_str .

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

Or, if you're using C++17 with its non-const std::string::data method:

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

Change

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

To

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM