Why is this fwrite writing garbage?

c++, fwrite, string

Solution

First of all, I suspect `s` contains some carriage returns. This causes the cursor to move the beginning of the line, with further output overwriting what's already been printed. To see the actual character that get printed, redirect the output of your program to a file, and then use a hex editor/viewer (e.g. `xxd`) to examine the result.

Secondly, `sizeof(s)` is not the right way to determine the length of a `std::string`. Use `s.length()` instead. This is why `numChars` is incorrect.

Lastly, to write the string to the file, use:

fwrite( s.data(), sizeof(char) , s.length() , DATA_LOG);

Problem

I'm building a program that takes in serial data and saves it to file. Each line of data is timestamped. In this code, the timestamped line of data is s. ``` string s = get_timestamp(); cout << "input string named s is: " << s << "\n"; numChars = sizeof(s); cout << "size is: " << numChars << "\n"; fwrite( &s, sizeof(char) , numChars , DATA_LOG); ``` The print statements output ``` 00000.27m,379named s is: 20130822.1141,00000.26m,379 size is: 28 ``` You can see that for some reason the "input string named s" seems to be overwritten. This isn't really my main concern though (though I don't know why it's happening.) My main problem is that my fwrite saves garbage to file. You can see that the numChars and string are correct. I've tried in place of "&s", "static_cast(&s)" with the same garbage results. Any ideas?

Original source