-3

I'm starting to learn C, and currently programming a little text-based lottery-like game. But I need a way to store the value in the end of the game, so it can be kept for the next plays. I made a simpler code below that represents what I need. Please help.

#include <stdio.h>

int main() {
    //TODO get "int saved" from save.txt
    printf("Value saved: %d\n", saved);
    printf("Add: ");
    int add;
    scanf("%d", &add);
    int new = saved+add;
    printf("New value: %d\n", new);
    //TODO save "int new" to save.txt
}

save.txt:

100
UToast
  • 3
  • 2
  • Google is what you need at the moment. Try that figure a bit of it yourself if problem still persist come here with a specific problem, Don't ask for whole solution here... – user2009750 May 03 '15 at 20:35
  • @ɢʜʘʂʈʀɛɔʘɴ Yes, problem does persist. All solutions I found were about arrays and/or multiple data in a file. And if I was actually asking for the whole solution, I'd have just slapped my whole code here and asked for a full fix. – UToast May 03 '15 at 20:43

1 Answers1

0

Try this

FILE *file;
int   saved;
int   add;

file = fopen("saved.txt", "r");
if (file == NULL)
 {
    fprintf(stderr, "error opening `saved.txt'\n");
    return -1;
 }

if (fscanf(file, "%d", &saved) != 1)
 {
    fprintf(stderr, "file `saved.txt' corrupted\n");
    fclose(file);
    return -1;
 }

fprintf(stdout, "please input an integer > ");
if (scanf("%d", &add) != 1)
 {
    fprintf(stderr, "invalid input\n");
    fclose(file);
    return -1;
 }
fclose(file);

file = fopen("saved.txt", "w");
if (file != NULL)
 {
    fprintf(file, "%d\n", saved + add);
    fclose(file);
 }
Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97