In: Computer Science
HW_6c - Append data to existing data in a file.
the results.txt file.
end of the existing data).
/* OUTPUT
Here are the numbers in the file:
3
4
5
Enter 3 more numbers:
6
7
8
The numbers have been written (appended) to results.txt.
Press any key to continue . . . */
Please make the code based on C++, and make a description for each code.
#include<iostream>
#include<fstream>
using namespace std;
/*main function*/
int main()
{
ofstream fout; // for writing to a file
ifstream fin; // for reading from a file
fin.open("results.txt"); // opening file
// used append mode which is used to append data at
the end of file
fout.open("results.txt",ios::app);
if(!fout && !fin){ // check if file not
open
cout<<"Error File not
found!"<<endl;
return 0;
}
int num; // to read number in variable
cout<<"Here are the numbers in the file:
\n";
while(fin>>num){
cout<<num<<endl; //
print content of file
}
cout<<"Enter 3 more numbers: "<<endl; //
take input
for(int i = 0; i < 3; i++){
cin >> num; // taking
input
fout<<"\n"<<num; //
writing to a file
}
cout<<"The numbers have been written (appended)
to results.txt."<<endl;
system("pause");
return 0;
}
/* Screenshot of a code for indentation */
/* OUTPUT */
/* results.txt */