Hi, I'm trying to make a save game system for my text adventures. I have no experience reading and writing files, so I wrote a test program to teach myself:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
fin >> x;
fout << x + 1 << endl;
When I run the program, save.txt contains the number 3 and a newline. So the program should read in a 3, then change the contents of save.txt to 4. But instead it prints the leftover memory that was dumped into x when it was declared (2130567169). How do I properly read in from and write to the same file?
ok, i also noticed you forgot to close the files in the first program. you need to do
or the file will be left open in the ram. this is not a great thing. remember when people tell you to always close files before closing them? this is the same kind of thing but instead of just losing info you are also losing space in your ram. the ram resets itself when you restart your computer so you do not actually have any damage. but if you are running like a gigabit worth of info in files and forget to close them you will almost always require a computer restart after the program runs.
While I am sure that this isn't the issue, the file is open in VS. When I write to a ifstream who's file is open in VS, VS will pop up "The file changed, do you want to reload". This doesn't happen with the code I posted.
Just from TheDestroyer's post. Without it I still have issues.
I think it has something to to with the write position. I tried all kinds of things last night (check to make sure the file is good, set the write position back to 0, etc). As soon as I extract from the file I can't write back into it.
VC++ and g++ differ here. g++ doesn't require the seek, VC++ does. Perhaps VC++ is nonconforming in this respect.
1 2 3
file >> data;
file << data +1;
This doesn't work for VC++ (when opened with ios::in | ios::out | ios::app) if there's a space after the number in the file, unless you also throw in a seekp() between the read and write. It does work when the number is followed immediately by the eof indicator.