Thread: Saving data

  1. #1
    Unregistered
    Guest

    Saving data

    I am writing a program where i need to save certain variables to the hard drive so that i can load them when my program runs again. What is the best way to do this? I have arrays of structures with strings in them and int*'s. Thanks for any help, i really don't know much about io. so any help is appreciated

  2. #2
    Just because ygfperson's Avatar
    Join Date
    Jan 2002
    Posts
    2,490
    simply write them to a file via the iostream classes.
    Code:
    ofstream out_file;
    out_file.open("this.txt");
    out_file << szText << x;  //there's undoubtedly a much better way to do this
    out_file.close();
    you might want to give some thought to how you're going to organize the file. i recommend writing small functions to keep track of every byte spent, so that only 4 bytes are dedicated to an integer, 8 to a double, and everything until a zero for a string. you might also want to put some characters marking the data type before you load it. opening looks like this:
    Code:
    ifstream in_file;
    in_file.open("this.txt");
    in_file >> variable1 >> variable2; //unrealistic
    in_file.close();
    if you want to skip right over any kind of security and optimizing, just put a newline between variables and load like so:
    Code:
    ofstream out_file;
    out_file.open("this.txt");
    int x; float y; char *z; //z might need to be initialized beforehand
    strcpy (z,"a cleverly worded message"); 
    
    out_file << x << endl << y << endl << z << endl;
    out_file.close();
    
    ....
    
    ifstream in_file("this.txt");
    in_file >> x >> y;
    in_file.getline(z);  //this could be wrong... check syntax to be sure
    in_file.close();

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 48
    Last Post: 09-26-2008, 03:45 AM
  2. singly linked circular list
    By DarkDot in forum C++ Programming
    Replies: 0
    Last Post: 04-24-2007, 08:55 PM
  3. saving data into a file
    By afrm in forum C Programming
    Replies: 4
    Last Post: 05-22-2006, 09:54 AM
  4. Saving Data
    By JoeJTaylor in forum C++ Programming
    Replies: 5
    Last Post: 04-22-2006, 09:06 PM
  5. C diamonds and perls :°)
    By Carlos in forum A Brief History of Cprogramming.com
    Replies: 7
    Last Post: 05-16-2003, 10:19 PM