Help with ofstream

Jun 15, 2016 at 7:02pm
So i met this problem. When i write an ofstream in more than 1 function, my results file "DD.txt" only shows the last ofstream that program did , which is "6". Is there a possible way to do something that my results file have both, 12 and 6 written in it? Thank you!

#include <iostream>
#include <fstream>
using namespace std;
void WOW(int x);
void WOW2(int y);
int main()
{
int a=12, b=6;
WOW(a);
WOW2(b);
cout << "Hello world!" << endl;
return 0;
}
void WOW(int x)
{
ofstream of("DD.txt");
of<<x<< endl;
}
void WOW2(int y)
{
ofstream of("DD.txt");
of<<y<< endl;
}
Jun 15, 2016 at 7:09pm
Calling the std::ofstream constructor by passing a path without passing any flags calls std::ofstream::open() passing the default flags. std::ios::trunc is part of the default flags, which truncates the file if it exists. To append to the file, pass std::ios::app as the second parameter to the constructor.
Jun 15, 2016 at 7:14pm
I don't really understand what are you trying to say over here cuz i'm noob. Sorry for that. Could you show me how my code supposed to look like? :/
Jun 15, 2016 at 7:19pm
 
std::ofstream file("foo.txt", std::ios::app);
Jun 15, 2016 at 8:00pm
In which part of my code should i put it?Everywhere where is "ofstream of("DD.txt");" ?
Jun 16, 2016 at 8:19am
yes^
Replace ofstream of("DD.txt") with ofstream of("DD.txt", ios::app);

The ios::app will append (add) to the file instead of overwriting. When you do not use a flag like ios::app, it just overwrites the existing data with the new data by default, which is what happened in your case (12 was overwritten by 6).

You might also wanna use of.close() once you are done with the file.
Last edited on Jun 16, 2016 at 8:22am
Jun 16, 2016 at 9:11am
You might also wanna use of.close() once you are done with the file.

In this case that isn't necessary. It is true that the file should be closed when the program has finished using it. However, the ofstream will automatically close the file when it goes out of scope. That is to say, the file is already being closed properly.
Jun 16, 2016 at 9:37am
Thank you guys so much! :)
Jun 16, 2016 at 10:18am
@chervil
Ah yes, my bad :) Cheers!
Topic archived. No new replies allowed.