appending a file

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...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
  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;

}



thanks for any help
you just need to open it once at the beginning of your code.
if you just want to keep on appending to the file.

1
2
3
4
5
6
7
8
// while you haven't finished
while (!quit)
{
 // ask for user data and do your calculations
 // append data to file.
}

//close the file here. 
what libray is !quit in? I just added that code to my program and it broke it...
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.
Last edited on
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.
added an extra function to run the program itself and main only opens and closes the files and calls the new function. thanks for the help.
Topic archived. No new replies allowed.