Search code examples
arrayscfilecounterincrement

How to count number of logins in C language


Well I'm making a program that initially asks to login or register.

I need to make a counter for each time the program is accessed (after the login).

C language using the array of functions and file Login Register

The method to log in and register follows the one up.

My thing is due to the lifetime of the var, because I know the moment the program ends the var just restarts.

So far I tried many ways. By macros but once again soon as the program ends it restarts. I'm starting now to make one saving in files.

I started just now so the function is very simple, but since I only have more 2 hours to deliver the work so I hope you guys help me.

Simple function:

enter image description here


Solution

  • At the definition of fp you should call the function fopen. From the documentation of fopen:

    w+
    Open for reading and writing. The file is created if it does not exist, otherwise it is truncated. The stream is positioned at the beginning of the file.

    The file gets truncated and you need to read it before you open it for writing.

    fp = fopen("contador.txt", "r");
    if (!fp) {
       perror("fopen");
       return -1;
    }
    fscanf(fp, "%d", &contador);
    fclose(fp);
    fp = fopen("contador.txt", "w");
    

    You can use fscanf for parsing the file and storing the value into your variable.