1

I am writing a program to organize some items. It starts off by getting the date/time and randomly generating a list of some items. But the next time you run it, the program shouldn't generate any of the same items as last time. So basically the date and time is like a seed for random generation.

But is there a way to store the data outside of the program? That way I can close the program and my PC, but when I return it still remembers the variable.

I've thought about it and it seems like the only way is to go in the program and manually define the variable. So I haven't tried anything yet and it would be pointless to show my code. Please tell me if there is a way to externally store the variable or if you have any alternate solutions.

Doggy-B
  • 47
  • 10

4 Answers4

2

You have two choices :

  • Using a file

    It's the easiest way to do this : The first time, you just need to open (and create) a file (man fopen), write your variable in it (man fwrite).

    Every next time, you'll need to open the file, and read your variable from it (man fread).

  • Using a database

    Harder, but better if you need to store many datas. This isn't your case, so just go with a file

4rzael
  • 679
  • 6
  • 17
2

General Idea is to use Non Volatile RAM . You can mimic the same by using a file. Need to take care of writing the contents of the context before closing the program and reading the same during the program startup. For programming with Files ,you can refer any of good sites.

1

To store the data externally, so that it is saved, use a file.(http://www.cplusplus.com/reference/cstdio/fopen/)

FILE *fp;

/* open a file in write mode */
if (fp = fopen("myfilename", "w")) {
    fprintf(fp, "Hello world");
    if (fclose(fp) == EOF) /* fclose returns EOF on error */
        perror("fclose");
} else
    perror("fopen");   /* error */

/* open the file in read mode */
char line[80];
if (fp = fopen("myfilename", "r")) {
    fgets(line, 79, fp);  /* read the first line */
    printf("%s", line);

    if (fclose(fp))
        perror("fclose");
} else
    perror("fopen");  /* error */
lost_in_the_source
  • 10,998
  • 9
  • 46
  • 75
  • I'm not generating the same numbers every time, I did use `srand(time(NULL))` I just needed a way to change the data in the file through the program – Doggy-B Sep 07 '15 at 14:08
0

Classical way to save many variables of different types is serialization. But there are no standard serialization method in C, so you need to implement your own or use existent (for example, tpl or gwser). If you need to save only one-two variables it is simplier to use fopen() + printf() + fclose().

Ilya
  • 4,583
  • 4
  • 26
  • 51