counter how many times the program was executed in C

Asked

Viewed 281 times

1

wanted a program that counts how many times it was executed through a txt file that quarda this value, but what happens is that it never leaves 1, someone has an idea of what I did wrong?

#include <stdio.h>

int main() {
    int numero_de_execucoes;
    FILE *total;
    numero_de_execucoes = 0;
    total = fopen("total.txt", "w+");

    if(total){
        while(!feof(total)){
            fscanf(total , "%d", &numero_de_execucoes);//lendo o ultimo numero_de_execucoes
        }
    }
    else{
        printf("ERRO");
    }

    numero_de_execucoes += 1;//incrementando + 1


    fprintf(total, "%d", numero_de_execucoes);//escrevendo no arquivo o 
                                              //numero_de_execucoes atual 

    fclose(total);
    printf("%d",numero_de_execucoes);//saida
}

1 answer

6


Looking at the documentation of fopen:

"w+" write/update: Create an Empty file and open it for update (Both for input and output). If a file with the same name already exists its Contents are discarded and the file is treated as a new Empty file.

This way you will always create an empty file, and then put information in it (in case your counter with 1).

I suggest you change your implementation to use something like fopen("total.txt", "r+");, according to the documentation:

"r+" read/update: Open a file for update (Both for input and output). The file must exist.

You must only ensure that the file exists, the file will be opened and its contents will be updated.

Reference here

Browser other questions tagged

You are not signed in. Login or sign up in order to post.