Your code can be written as
ofstream file1("lastServers.bin", ios::out | ios::binary); if (file1.good()) { file1.write(ip.c_str(), ip.size()); file1.write(port.c_str(), port.size()); file1.close(); } else { std::cout << "file error write" << endl; }
string :: c_str () returns a const pointer to the text in the string. string :: size () returns the number of characters in a string.
You do not need to concatenate the data before writing to the file, writing one, and the other has the same result.
If you want to write code like C, not C ++, you can use strlen (p_IP) to get the length of the IP string, rather than using sizeof.
The sizeof operator gives the size of the class instance, i.e. the size of the object, but the size of the string object never depends on the size of the string it controls.
In C ++, objects that control something (think that strings that control characters, containers that control their contents, etc.) usually have a method for determining the size of what they control. For std :: string and other STL containers, this method is size ().
Note that writing these lines in this format means that you cannot specify where one line ends and the other begins. Two possibilities for consideration are to use a trailing character, which, as you know, will not be displayed on any line, or write the length of a line to a file before the text of the line itself. I will not stop here, because in the initial question he was not asked.