0

I am making a text based game and want the user to be able to save. When they save all the variables will be saved to a text file.

I can't figure out how to take them out of the file and assigning them to specific variables and pointers.

The file will look somewhat like this:

jesse
hello
yes
rifle
0
1
3
20

Is there anyway I can specify what line I want to take out with fscanf? Or do I have to take a different approach?

3 Answers 3

1

There is no way to specify what line to read from because the concept of a file stream in C does not explicitly distinguish new lines. They are simply treated as a character. To read from a specific line, you would have to loop forward with fseek and fgetc until you find '\n' at which point you can update some variable that holds the current line number the stream points to.

One way around this would be to have information at a fixed offset. For example, say you are storing player information then if you make player information a fixed size X and have the constituent data at fixed indexes into each structure, you can just fseek to the right location straight away.

However, if you have structured data, it may be more suitable to use a format which is able to represent these structures inherently such as XML or JSON.

Sign up to request clarification or add additional context in comments.

Comments

1

Altough I can't exactly tell what you want, I'd do a few suggestions:

  • Use a SQLite file instead of a text file. This way you can use SQL to get exactly what you want. Shortcut for you: http://www.sqlite.org/

  • If you still want to use a text file, use it comma-separated instead of spaces-separated. It's more common of a practice.

1 Comment

k thx idk SQL though... so seperate them with commas. Sorry i guess i am not being clear. Lets say someone has 2 health left in the game, i want to save 2 to the file so next time they come on there health will be at 2. i also want to store there name in the file so how basically how do i read things from a file and store diff things in diff variables. Sorry i am terrible at describing this lol
0

I have created a simple settings reader for my C program, maybe it might be useful to you to know how to parse test files https://codereview.stackexchange.com/questions/8620/coding-style-in-c

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.