Writing to a Data File
For the second part of my assignment, I have to write some data to a file, but I can't find notes anywhere in my textbook or class notes that explain how to do something like this:
"The second output requirement for this program is to save class roster in a data file. It needs to include only students names and final scores. The format should look like:
Terri Smith 70
Mary White 90
Pete William 80
Harry Lia 100
Amy Peterson 60
Don't forget to close the file at the end!"
Excellent, thanks a lot!! :D
That tutorial is out of date and uses the non-standard fstream.h header. There are a few small differences between fstream and fstream.h, so be careful.
Do you know how to output to cout? It is almost exactly the same, except you need to create an ofstream object. For example, if you create an ofstream variable called fout, then just output your data to fout instead of cout.
>> Don't forget to close the file at the end!
Hopefully your instructor knows that a file stream closes automatically when it goes out of scope and its destructor is invoked. There is no need to close it explicitly.
if you wish to write a class object into file , then do the following using fstream object
where filename.ext is any file that you wish to use. ios::binary for the write mode, and the format for writing an object to file using the write function. parameters of this fstream defined function are the object and the size.
hope this helps you out!
Your "class" should have only POD types if writing it out that way in binary. If it has any members that use dynamic memory like std::string then it won't work.