In my game i would like to have a function that writes the balance of the player to a file, i have already made a file and got a function to read it and put it into a variable put i need help with changing the file when i call this new function
I basically want to overwrite the file completely but i dont know how
By default, an std::ofstream opens a file with std::ios::out, which essentially deletes the contents of the file, and provieds a stream that can be written to. This will provide the function you want.
Example:
1 2 3 4
std::string a_file{"whatever you want"};
std::ofstream out{a_file.c_str(), std::ios::out};
//now if you want to close it, the contents of the file are erased.
//this does not remove the file itself, though.
Note that if you want to delete a file, you will have to use the operating system's API. However, the Boost library provides a cross-platform solution that I find much more preferable.
I have a problem: how would i do it if all i want to do is write a number? Because all i want it to do is write the balance of the customer to a .txt file, so it is stored and can be accessed if the program is exited and then run again
1. As Texan40 and IWishIKnew said, by default an ofstream is opened for overwrite (you only have to do something if you want to append to the existing file.)
2. So removing the file is not necessary (you're getting the o/s to do work unnecessarily.)
3. And ofstream::close() is called by the ofstream destructor.
4. And return; is not needed (as there's nothing to return.)
OK, so all these issues are benign. But when coding you should be aiming for the minimal and complete solution.
Apart from anything else, I'm far too lazy to type unnecessary code! :-)
Andy
PS If I was going to add code to this function, it would be for error handling.