user2619824
user2619824

Reputation: 478

Why is this fwrite writing garbage?

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?

Upvotes: 3

Views: 1666

Answers (3)

CodeAngry
CodeAngry

Reputation: 12985

sizeof(s) should really be strlen(s) or wcslen(s).

Or if you're using the std::basic_string<>, .length() will give you the length and .c_str() will give you the char string pointer, not &s which is the pointer to the actual object.

So try:

if(!s.empty()){
    fwrite(s.c_str(), sizeof(s.front()), s.length(), DATA_LOG);
}

Upvotes: 0

NPE
NPE

Reputation: 500167

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);

Upvotes: 4

Mats Petersson
Mats Petersson

Reputation: 129314

Writing a std::string s to a file would look something like this:

fwrite(s.c_str(), 1, s.size(), DATA_LOG); 

There may be other issues with your data, looking at the console printout, but I'm not sure without seeing the actual data in a debugger or similar.

Upvotes: 1

Related Questions