Note that there are some explanatory texts on larger screens.

plurals
  1. POReading std::string from binary file
    primarykey
    data
    text
    <p>I have a couple of functions I created a while ago for reading and writing std::strings to a FILE* opened for reading in binary mode. They have worked fine before (and WriteString() still works) but ReadString() keeps giving me memory corruption errors at run-time. The strings are stored by writing their size as an unsigned int before the string data as char.</p> <pre><code>bool WriteString(std::string t_str, FILE* t_fp) { // Does the file stream exist and is it valid? If not, return false. if (t_fp == NULL) return false; // Create char pointer from string. char* text = const_cast&lt;char*&gt;(t_str.c_str()); // Find the length of the string. unsigned int size = t_str.size(); // Write the string's size to the file. fwrite(&amp;size, sizeof(unsigned int), 1, t_fp); // Followed by the string itself. fwrite(text, 1, size, t_fp); // Everything worked, so return true. return true; } std::string ReadString(FILE* t_fp) { // Does the file stream exist and is it valid? If not, return false. if (t_fp == NULL) return false; // Create new string object to store the retrieved text and to return to the calling function. std::string str; // Create a char pointer for temporary storage. char* text = new char; // UInt for storing the string's size. unsigned int size; // Read the size of the string from the file and store it in size. fread(&amp;size, sizeof(unsigned int), 1, t_fp); // Read [size] number of characters from the string and store them in text. fread(text, 1, size, t_fp); // Store the contents of text in str. str = text; // Resize str to match the size else we get extra cruft (line endings methinks). str.resize(size); // Finally, return the string to the calling function. return str; } </code></pre> <p>Can anyone see any problems with this code or have any alternative suggestions?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload