saving & loading user info

dumbhound's Avatar, Join Date: Jan 2007
Newbie Member
Hi guys, my first few days in c++ have been fun and headache-free, but I have run into one question that isn't addressed as a whole topic in the primers I'm reading. I don't need code help or even syntax, I just need to know whether what I'm wanting to do eventually is possible: have the program write info to a file and call it up again once the program has terminated, plugging in the appropriate variables.

my big first project that I imagine any beginner programmer has is a command-line game to simulate a telnet environment and play a mean ole blackhat. Nothing I've read so far tells me I'll be able to output a file that the user calls up to re-plug his saved variables into the program. If I've got the wrong idea, please give me some indication of how I will wind up saving a user's accumulated data.

thanks much!
hide's Avatar, Join Date: Jan 2007
Newbie Member
Yeah, if you can do it, you can do it in C++.

You can get access to files through the fstream header. They work like cin/cout.
#include <fstream>
#include <ostream>
#include <iostream>

int main()
   fstream file("somefile.txt");
   if (!file) return 1; // could not open file
   int sum = 0;
   while (!file.eof()) { // while there's input in the file
      int value;
      file >> value; // get an integer from the file
      sum += value;
  file.close(); // close the file
  std::cout << "Sum: " << sum << std::endl;

Last edited by shabbir; 25Jan2007 at 11:06.. Reason: Code formatting.
DaWei's Avatar, Join Date: Dec 2006
Team Leader
You have to design the program such that a situation can be described by variables. Save the variables, get them back, and reconstruct the situation. Saving the precise, actual state of the program is extraordinally difficult but rarely necessary.

Depending upon your implementation, you can usually use signals or events to save important state even when program termination is abrupt and unexpected. In Windows, for example, your process will get about 20 milliseconds to clean up even if the big 'X' is clicked or logout/shutdown is instituted.