c++ - properly writing std::string to binary file

I am trying to get <strong>strings</strong> from cin and than write it to binary file. I've read that writing pure string won't work, so I tried to convert it to char*.

The following code writes it ok (...probably), but <strong>only the first 8 chars, so the output in file is incomplete.</strong>

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; } <hr>

<strong>Thanks in advance for any help :)</strong>

Answer1:

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 the string.

You don't need to concatenate the data before writing to the file, writing one then the other has the same result.

If you wanted to write C type code rather than C++, you can use strlen(p_IP) to get the length of the IP string rather than using sizeof.

The sizeof operator gives you the size of the class instance, i.e. the size of the object BUT the string object's size is never affected by the size of the string it manages.

In C++, objects that manage something (think strings managing characters, containers managing their contents, etc.) usually have a method to determine the size of what they're managing. For std::string and other STL containers that method is size().

Note that writing these strings in this format means you can't tell where one string ends and another one starts. Two options to consider are using a terminating character that you know won't appear in any strings, or writing the length of the string to the file before the text of the string itself. I won't elaborate here as it was not asked in the original question.

Answer2:

sizeof returns you the size of the string object in the memory, not the length of the string itself. Specifically, sizeof(&p_IP) returns the size of the pointer to p_IP, which is always 4 bytes on a 32-bit system. Your variable length simply does not compute to the correct value. To get the length of a char*, use strlen.

人吐槽 人点赞

Recommend

Comment

用户名: 密码:
验证码: 匿名发表

你可以使用这些语言

查看评论:c++ - properly writing std::string to binary file