-
write() function
I managed to write type of string as following
Code:
ofstream& operator<<(ofstream& stream, const Data& d) {
int len;
char *str;
str = new char[80];
string name = "me";
len = static_cast<int>(d.name.length());
strncpy(str, name.c_str(), len);
stream.write(reinterpret_cast<const char *>(&len), sizeof(int));
stream.write(reinterpret_cast<const char *>(str), len);
return stream;
len = static_cast<int>(sizeof(d.num));
stream.write(reinterpret_cast<const char *>(&len), sizeof(d.num));
stream.write(reinterpret_cast<const char *>(d.num), len);
}
The overloaded operator above is supposed to work for:
outFile << Data;
But I cant get the d.num to print.
any clue??
-
I can't understand what you are trying to do, however, using reinterpret cast to make an int a char pointer is a very bad idea to my mind... There's cases where it might be useful anyway.
-
I complete the codes above for clarity (see 1st post). So, how would you write an integer using above method?
edit: the method above write the length field followed by the content
-
My question is still what are you trying to do with all that code. Normally, when just outputting, you'd do:
stream << d.name << " " << d.num << endl;
and it would work fine. What are you trying to do with the casts and sizeof stuff?
-
Ok, just saw your edit. So you are trying to output the length of the field as in how many characters will be printed out, followed by the field itself?
Maybe convert the int to a string using a stringstream and then do your little thing for that string.
-
Ok, here's my suggested version. You must #include <sstream>.
Code:
ofstream& operator<<(ofstream& stream, const Data& d) {
stream << d.name.length() << d.name;
// Convert int to string using string stream.
stringstream numStream;
numStream << d.num;
stream << numStream.str().length() << numStream.str();
return stream;
}
-
-
Okay, if you're still with me. I managed to write both type of string and of integer. I figured how to read back the type of string, but came up with nothing for type of integer after hours. Any idea
Code:
// codes to write string d.name
len = static_cast<int>(d.name.length());
strncpy(str, name.c_str(), len);
stream.write(reinterpret_cast<const char *>(&len), sizeof(int));
stream.write(reinterpret_cast<const char *>(str), len);
return stream;
//codes to read string d.name and set it
stream.read(reinterpret_cast<char *>(&len), sizeof(int));
stream.read(reinterpret_cast<char *>(strTmp), len);
strTmp[len] = '\0';
d.setName(strTmp);
// codes to write int d.num
outStream << d.num;
len = static_cast<int>(outStream.str().length());
strncpy(str, outStream.str().c_str(), len);
stream.write(reinterpret_cast<const char *>(&len), sizeof(int));
stream.write(reinterpret_cast<const char *>(str), len);
outStream.str("");
// codes to read int d.num back????
Note that I use write() because I write the file in binary mode
-
Nevermind! I figured it out. I use atoi() to convert char * to int.