fstream -- writing to files

hi, I am new to C++ and new to this forum, sorry for being a noob.
i and using Dev-C++ as my compiler

i need to know how i can erase a file using the fstream or some other command. I am creating a game, and I can open the file to load a saved game (.txt file), but when i try and save the to a .txt file I need it to erase it information first. heres the code for saving the program (which i am having problems with):

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <fstream>

using namespace std;

int main () {
int money;
fstream myfile;
myfile.open ("save/moneyt.txt");
myfile << money;
myfile.close();
}

this code works just fine, just doesn't do what i want it to.

the file "save/money.txt" has "20" in it.
if "int money" is less than 10(lets say its 4 for example), once compiled and run, the program replace the 2 (from the 20 in original file) with '4' and then "save/money.txt" will have '40' in it, instead of '4' which is what i want


so really, my question is how do I delete the contents of the file first, so the program will write the new value in the .txt file?

any help would be great!
Unless the std::ios::app flag is used, files are emptied upon being opened.
If that's all your code, then you didn't initialize 'money', so you have no way of knowing what is being written to the file. It's contents are the value of 'money'.
ok, so even replacing the:
int money;
with
int money = 4;
did the same thing.
thats not all my code, there are a few more lines in this script that i didn't post, because it woul have been repeative... lol.

so your saying that it automatically should delete the contents of the file before writing it unless i put
myfile.open("save/money.txt",std::ios::app);
?
Last edited on
i just figured out that it is easier to jut put a bunch of spaces after the variable:
 
myfile << money<<"  ";

which erase the file for me. :D
Last edited on
That doesn't make any sense. Are you sure that works? Even if it does, that's a very bad solution you got there.
What compiler are you using? The default might not be using the std::ios::trunc flag, try passing it yourself.
As helios said - just writing a bunch of spaces is not the way to go.

The default open mode for a file is ios_base::in and ios_base::out

To empty a file when you open it, you add the truncate mode.

myfile.open( "save/moneyt.txt",ios_base::in|ios_base::out|ios_base::trunc );
Oh, look at that. I didn't notice it. That's why it's not truncating the file.
You opened it as read/write, so it can't just empty it (what would happen if you tried to read it, first?).
Instead, open it like this:
 
std::ofstream file("name.txt");

That should automatically truncate the file.
Topic archived. No new replies allowed.