Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   saving & loading user info (http://www.go4expert.com/forums/saving-loading-user-info-t2692/)

dumbhound 25Jan2007 02:56

saving & loading user info
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 25Jan2007 10:12

Re: saving & loading user info
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;

DaWei 25Jan2007 19:49

Re: saving & loading user info
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.

All times are GMT +5.5. The time now is 01:58.