58905

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

  • Storing the IV with the ciphertext Crypto++ CBC AES encryption
  • Linked List From Text File
  • fstream get(char*, int) how to operate empty line?
  • Sending a C# string as an argument to a unmanaged C++ DLL function
  • C/C++ System portable way to change maximum number of open files
  • Fetch/Refresh Health Kit Data Programmatically?
  • F# signature file error
  • Complete data loss Ionic / Cordova LocalStorage and Websql iOS 8.4.1
  • How to style GCKUIMiniMediaControlsViewController in iOS?
  • F# NativePtr.stackalloc Unexpected Stack Overflow
  • Ansible sudo hangs after 5 tasks
  • chrome PDF viewer can't download file
  • C++ Text File Reading
  • Print: Entry, “:CFBundleIdentifier”, Does Not Exist have tried most solutions
  • No such module 'Parse' following Parse iOS Swift Quickstart guide
  • Retrieve Facebook Account Information in ios 6
  • JavaScriptCore External Arrays
  • How to create virtual printer with iOS Simulator?
  • Save image as is in photo album using swift
  • iOS Cordova first plugin - plugin.xml to inject a feature
  • PushKit for VOIP iOS apps
  • Facebook iOS SDK Not Calling Completion Handler
  • Jenkins: FATAL: Could not initialize class hudson.util.ProcessTree$UnixReflection
  • C: Incompatible pointer type initializing
  • Custom Tabgroup Appcelerator
  • Different response to non-authenticated users and AJAX calls
  • C# - Serializing and deserializing static member
  • JavaScriptCore crash on iOS9
  • AES padding and writing the ciphertext to a disk file
  • VS2008 Enable C++ Exception with SEH
  • Incrementing object id automatically JS constructor (static method and variable)
  • Do create extension work in single-user mode in postgres?
  • Rearranging Cells in UITableView Bug & Saving Changes
  • How get height of the a view with gone visibility and height defined as wrap_content in xml?
  • FormattedException instead of throw new Exception(string.Format(…)) in .NET
  • Sorting a 2D array using the second column C++
  • How to Embed XSL into XML
  • UserPrincipal.Current returns apppool on IIS
  • Conditional In-Line CSS for IE and Others?
  • java string with new operator and a literal