Writing a save file

Okay, so I have looked online for writing save files. I followed exactly what they
said to do. here's the source code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//This is the region that defines the function for saving
#pragma region Save Game
void saveGame()
{
    ofstream mySaveFile;
    mySaveFile.open("save.txt", ios::out | ios::app | ios::binary);
    while (mySaveFile.good())
    {
        mySaveFile.open("save.txt");
        mySaveFile<<"Here are the items:"<<endl;
        mySaveFile<<item1;
        mySaveFile<<item2;
        mySaveFile<<item3;
        mySaveFile<<item4;
        mySaveFile<<item5;
        mySaveFile<<"Here are the rooms/levels:"<<endl;
        mySaveFile<<level;
        mySaveFile<<room;
        mySaveFile<<"Here's the character's name:"<<endl;
        mySaveFile<<characterName;
        mySaveFile<<flush;
    }
}
#pragma endregion 


is there ANYTHING wrong in the code? if so, please tell me
Last edited on
you should close the file when you're done and change the while-loop to an if-statement. This looks pretty much like an infinite loop to me.

This might also help you a bit: http://cplusplus.com/doc/tutorial/files/

Edit: Oh and you open the file twice, that makes no sense.
Last edited on
There are a few things wrong with the code.

1) You are opening the save file on line 6. So why are you opening it again on line 8? It's already open.

2) Your loop on line 7 is pointless. That will just deadlock your program unless the file fails to open because it will keep looping.

3) You need to be able to read back the data you write, which means you'll need to have some kind of division that you can identify. As it stands now you're writing a file that might look like this:

item1item2item3item4item5levelroom


Notice how all the names are mushed together. How do you expect to separate them when you load this file?

Assuming all these strings are 1 line each... you can separate them by putting a new line between them.

4) There's not much need to put human-readable descriptors in the file unless you're expecting the file to be human readable. ie: "Here are the items:" contributes nothing to this file. I would say get rid of it.
Okay. Thanks for the help.
I managed to get it working
Topic archived. No new replies allowed.