File Handling in C++: Data Output

Written by Ali on. Posted in C++

As we have already learnt, file handling in c++ is a very strong and important tool to assist us with our work. File handling can save us a lot of trouble and can save us some really good amount of time. File Input methods and advantages  have been previously discussed, now we start over on data output and how to save information in a separate file for later use.

Data output to the file can help store information in a file for later use or just for the sake of saving the record. The procedure is very much the same as the input and the data output can be done in any type of file you want it to be. Unlike the input file where the name of the file has to be specified before, the name of the output file does not matter and can be any name you want it to be. The data output file need not to be present in the project folder, it can be automatically created by the name you have specified to open. Just for sake of reference, we consider the same old student data record, just like the last time and see what we need to do to output information to a file.

<p>//Continuation from the code in the last post…..</p>
<p>oftream fout;</p>
<p>fout . open(“output.txt”);</p>
<p>fout &lt;&lt; name &lt;&lt; “\\t”;</p>
<p>fout &lt;&lt; rollnumber &lt;&lt; mid1 &lt;&lt; mid2 &lt;&lt; final &lt;&lt; FinalMarks &lt;&lt; grade;</p>
<p>fout .close();</p>


What really happens here is that there is no file present in the project folder by the name of “output .txt”. C++ automatically creates a file by the name of ‘output’ and starts operating on it. As the data is already saved in the variables, all you need to do is to output it.

The process begins by first creating a variable of the ofstream type, let it be fout. The variable opens up a file, or creates one if not present for data output. Then simply output all the information you want to be output to the file. The procedure is simply the same as that with cout. Except for outputting the information on the console, it outputs the information in a file. Honestly, outputting isn’t much a big deal compared to inputting information in the system.

That’s it for now people. Keep your eyes sharp for next post.

Tags: ,