ofstream.write("blah.txt",ios::outios::binary)
Say you have this struct:
struct WebSites
{
char SiteName[100];
int Rank;
};
You could write it to a file like this:
void write_to_binary_file(WebSites p_Data)
{
fstream binary_file("c:\\test.dat",ios::out|ios::binary|ios::app);
binary_file.write(reinterpret_cast<char *>(&p_Data),sizeof(WebSites));
binary_file.close();
}
It casts p_Data as a char* and writes the whole struct to "c:\\test.dat". But it only works because sizeof(WebSites) yields the exact size that every Websites is. 104 bytes, I suppose.
But what if there was dynamic memory? Like char *SiteName; and Sitename=new char[150];?
Then is there any way to output to a file really simply like above? Or do you just have to write a more complicated function?
Check out boost::serialization. http://www.boost.org/doc/libs/1_38_0/libs/serialization/doc/index.html
you would either need to know the size of the char * if its terminated correctly you can scan along the string till you find the \0 termination char or you would need to hold the string length as a member of the struct to know how many chars to serialize out. In either case you would need to write out the separate parts of the struct using separate writes. To read in you would just read the whole lot of data into memory and cast that memory region to your struct. It is much easier to use an existing library to do this for you but it is also a good learning excersize to do it yourself. good luck
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement