is there a way to open a file when you 1st run a program - as if it were new - then open it later and append it?
I have a program that asks for information from the user - does some calculations and outputs it to a file, then asks if they would like to repeat the process - if they say yes I want the data to be added to the existing file. if they say no it closes. but what keeps happening is when I run the program for 1st time - it appends the file from last time...
void main()
{
outputfile.open("firstDigits_result.txt",ios::app);
if (!outputfile)
{
cout<<"Error! Output File did not open!\n";
system("pause");
return;
}
int numDigits=0, firstDig=0, nbr;
nbr=getData();
firstDig=firstDigit(nbr);
cout << firstDig << " is the first digit of " << nbr << endl;
outputfile << firstDig << " is the first digit of " << nbr << endl;
outputfile.close();
rinse();
system("pause");
return;
}
I think that rafae11 was just showing an outline, in effect just pseudo-code to indicate the logical structure. Here quit is just a boolean variable which the user would define and set to true or false as appropriate.
As for the original question. I think all that is required is to omit the ios::app when opening the file, as that is the cause of the unwanted behaviour - it makes the program retain the existing data from any previous execution.
Since (I think) you want to start afresh each time, you don't need to open it in append mode. Simply open the file at the start of the program and let it remain open throughout. When the program ends, the file can be closed.
only problem with taking the ios::app out is that I have a function that allows the user to run it again... and when it does that - it wipes everything out and only puts the last thing in the file.
Depends on what you mean by "allows the user to run it again". If the entire program is run again, naturally it will wipe out everything previous.
But if the file is opened at the start, closed at the end, and it is the code in the middle which is "run again", there is no way it could get wiped out.
I'd suggest the logic needs a re-think, share more of your code if you want a more useful opinion, otherwise its just guesswork.