0

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.

1
  • &retrived_str -- This points to the object, not the underlying buffer that holds the characters. Commented Apr 8, 2018 at 6:02

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.