I'm trying to write a text based game using C. To do this the way I want, I need to include a save system that will output all of the necessary variable values to external files, then be able to load the values fro those files later. Any advice?

Recommended Answers

All 11 Replies

What kind of variables? Are we talking just scalar values or data structures? The former are easy to export, but the latter could take a little thinking to get a format that's easy to both export and subsequently import.

ints. lots and lots of ints...

Any flat file format will work then. CSV is a common one, and if you're not going to have embedded commans in your values, the format is both simple and easy to parse.

what would I put in my code to save to that?

Let's step back a moment. How well do you know C? Granted I didn't provide details, but what I said should be enough to get you started unless you're a total beginner with no clue how to read and write files or about basic string manipulation.

your definition of a total beginner sounds a lot like me, I'm a freshman in college taking a C-programming course and the teacher is terrible

I'd recommend writing the value of the variables to a text file, and tag each value with the name of the variable. That way you can change the program to add more or remove some variables without changing the format of the file. An old *.ini file format is good for that, for example

[Mary] // player name
a=123
b=345
c=789
doorNumber=1
[DonkeyKong] // another player name

good news! i figure it out! I tested it using an array with a length of "length".
to output, I used

    file = fopen("output.txt", "a");
    for ( i = 1; i <= length; i++ )
    {
    fprintf(file, "%d""%s" , array[i], " ");
    }
    fclose(file);

then to read, I used

file = fopen("output.txt", "r");
for ( i = 1; i <= length; i++)
{
fscanf(file, "%d", array[i]);
}
fclose(file);

fprintf(file, "%d""%s" , array[i], " ");

Why %s when all you want is a space

fprintf(file, "%d " , array[i]);

my bad, took me a while to figure that one out :P just wasn't used to fprintf and was confused because only the varaible identifiers have quotes

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.