Hi! Im trying to make a c++ program for a school project, and i need to store the information into binary files, but I'm having some problems trying to store a class with string members, for example:
class whatever{
protected:
string name;
public:
(List of functions)
}
But if I do that, my code just dont work when I write and read a binary file, but if I change the string to char array, for example:
class whatever{
protected:
char name[20];
public:
(List of functions)
}
It works good, so I wanted to know if there's some way to store a class wiht strings in binary files, or what am I doing wrong?
so I wanted to know if there's some way to store a class wiht strings in binary files,
Yes it is possible, but it takes some work. First you're going to have to write each individual member variable one at a time. Second when it comes to the std::string it get's complicated because of two issues. The first issue is that if you just try to write the string with the write function you'll end up just writing the value of the pointer to the internal buffer, not the actual data. Secondly the std::string is not a fixed size so you will need to know the length of the string in order to read the string again. You can accomplish this all by first writing the length() of the std::string then writing the actual string using the c_str() function.
A unique terminator doesn't help when using the read() function to retrieve the string because you need to know how many characters were written with the write() function. The number characters you read() must match the number of characters you used when you called the write() function. And the c_str() function does provide the end of string characer ('\0'), but remember a binary file can and often does contain any character.
A unique terminator doesn't help when using the read()
Who forces you to use read()? There is a function in standard library which allows you to read until you encounter specific yser-provided delimiter. It is called getline().
but remember a binary file can and often does contain any character.
It contains characters you write. If your string does not contains vertical tab (and frankly I never seen one used in normal text) character, you can use freely as terminator. This is why I said "followed by unique terminator character which does not exist within string". It does not have to be \0.