Save better punctuation in a game

1

I have to save the best score obtained from a game made in C in a file: the functions I can use are fopen , fclose , fprintf , fscanf . I tried to do it like this:

int puntos=0;;;
if (lo que sea)
{
puntos=puntos+1;
}
 FILE * f_mayor_puntuacion = NULL;
    f_mayor_puntuacion = fopen("record.txt","r");
    int recordactual=fscanf(f_mayor_puntuacion,"%d",&recordactual);
    fclose(f_mayor_puntuacion);
    if (puntos>recordactual)
    {
        f_mayor_puntuacion=fopen("record.txt","w");
        fprintf(f_mayor_puntuacion,"El record actual son %d puntos",puntos);
        fclose(f_mayor_puntuacion);
    }

The problem is that the variable recordactual is always 1, so the file is always updated with the points even if it has not achieved the highest score, and I can not think of another way to do it. Could someone help me?

    
asked by paradise85 10.04.2018 в 22:40
source

2 answers

1

According to your approach it is necessary to do 2 activities that you have already identified. The first is to read the score, now you do it with the following instruction:

int recordactual=fscanf(f_mayor_puntuacion,"%d",&recordactual);

The above is wrong, the fscanf function reads the file data according to the pattern of the second parameter "% d" and stores the value in the third parameter < strong> & recantact , in this case it reads a number. The problem is that at the same time you are saving the result of the fscanf function in the same variable in which you intend to save the recall score, the fscanf function. strong> DO NOT return the value read but the number of items that could read and that agreed with the pattern, this misuse causes the value read from the file to be replaced by the value returned by the function, so always the variable Recall ends with the value 1 . In summary, the correct way to read the value is:

fscanf(f_mayor_puntuacion,"%d",&recordactual);

The second activity is to write the value as long as the score is greater than the previous one, I observe that you do it with the following instruction:

fprintf(f_mayor_puntuacion,"El record actual son %d puntos",puntos);

Which in general is not bad, however I have an observation, and that is that you are saving a message with the score, this message does not comply with the original standard of the file that is only a number, that is to say that in the next execution the file could not be read correctly, additionally this will not generate an error, but it will affect your program because the value read will always be zero since the function scanf can not find a numeric pattern in the read data.

By doing all the adjustment according to what I mention, the program should work without problems.

    
answered by 10.04.2018 / 23:32
source
0

By the way you read the file, I think the problem is what you write in it. You should only write the score:

fprintf(f_mayor_puntuacion,"%d",puntos);
    
answered by 10.04.2018 в 22:42