• Advertisement
Sign in to follow this  

ofstream.write("blah.txt",ios::outios::binary)

This topic is 3229 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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?

Share this post


Link to post
Share on other sites
Advertisement
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

Share this post


Link to post
Share on other sites
Thanks. I was just checking making sure that I was right that I'd have to write all the parts manually, instead of like the example above.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement