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);