C ++ - correct writing std :: string to binary

I am trying to get strings from cin and write to binary. I read that writing a clean line would not work, so I tried converting it to char *.

The following code writes it in order (... maybe), but only the first 8 characters, so the output in the file is incomplete.

std::string nick, ip, port; std::cout << "IP: "; std::cin >> ip; std::cout << "port: "; std::cin >> port; ofstream file1("lastServers.bin", ios::out | ios::binary); if (file1.good()) { const char* p_IP = ip.c_str(); const char* p_PORT = port.c_str(); int length = sizeof(&p_IP)+sizeof(&p_PORT); char* tmp1 = new char[length]; int index = 0; memcpy((tmp1 + index), p_IP, sizeof(&p_IP)); index = index + sizeof(&p_IP); memcpy((tmp1 + index), p_PORT, sizeof(&p_PORT)); file1.write(tmp1, length); file1.close(); delete[] tmp1; } else { std::cout << "file error write" << endl; } 

Thanks in advance for any help :)

+2
source share
2 answers

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.

+4
source

sizeof returns the size of the string object in memory, not the length of the string itself. In particular, sizeof(&p_IP) returns the size of a pointer to p_IP , which is always 4 bytes in a 32-bit system. Your length variable just doesn't calculate the correct value. To get the char * length, use strlen .

+1
source

Source: https://habr.com/ru/post/1415854/


All Articles