In c++ can you output to a output file then reopen the output file again to output something else under the original output.
for example, I open the output file then output the heading then close the output file.
Then reopen the output file and output some data under that heading then close it again.
But when i try to do that, my heading gets deleted and it only outputs the data
I would output the heading to the output file here: ID# NAME BALANCE
Then I close it, then try to output the data under it. For example: 1001 Johnny 1050.00
It would override the header and just output the data
So rather than have this in my output file
ID# NAME BALANCE
----------------------
1001 Johnny 1050.00
It would only have this in the output file:
1001 Johnny 1050.00
Here is my function to output the header:
void OutputHeaderToFile(string outFileName)
{
ofstream fout; /** allows the ability to use fout **/
fout.open(outFileName.c_str());
fout << "ID #" << left << setw(20) << "Name" << setw(21) << "BALANCE DUE" << endl;
fout << right;
fout << "----" << left << setw(20) << "--------------------" << setw(20) << "-----------"
<< endl;
fout.close();
}
It will output
ID #Name BALANCE DUE
-----------------------------------
Then I have another function to output the data under that heading.
void OutputDataToFile(string nameArray[], int idArray[], float balArray[], string outFileName)
{
ofstream fout; /** allows the ability to use fout **/
fout.open(outFileName.c_str());
fout << idArray[searchIndex] << " " << nameArray[searchIndex] << " " << balArray[searchIndex];
fout.close();
}
and I have included #include <fstream>
in my header file.
A std::ofstream
can be opened in overwrite mode (the default) or append mode.
If you know when to open in overwrite model, use:
fout.open(outFileName.c_str());
If you are able to use a C++11 compiler, that can be:
fout.open(outFileName);
If you know when you want to open the file in append mode, use:
fout.open(outFileName, std::ofstream::app);
or
fout.open(outFileName, fout.app);
Since you are not opening the file in append mode, its contents get overwritten when you open the file the second time.