0

im working in temperature logger, im using c to make it, the program has some functions, one of these is to calc the average of temperatures in a file, for this i use this code:

void promedio(void){
struct s_mediciones medicion;
struct s_promedios promedio;
FILE *mediciones;
float prom, sum = 0;
int cont, linecount = 0;

if((mediciones=fopen("mediciones.txt","r"))==NULL){
    printf("\nError al abrir/crear el archivo.");
    getch();
    exit(1);
}

system("cls");

while(!feof(mediciones)){
    for(int i=1;i<5;i++){
        fread(&medicion, sizeof(medicion), 1, mediciones);
        if(cont % 4 == 0){
            sum = 0;
        }
        sum += abs(medicion.temp);
        cont++;
    }
            
    promedio.valor = (sum/4);

    if(linecount % 1 == 0){
        printf("---------------------------------------\n");
    }

    printf("El promedio del %s es: ", medicion.fecha_med);
    printf("%.1f %cC ", promedio.valor,248);
    printf("\n\n", linecount++);
    
}

printf("\nPulse una tecla cualquiera para salir...");
getch();
fclose(mediciones);
system("cls");

}

The problem is that when it prints the listing of averages it repeats the last line, i know that the while(!feof) is causing that, and i read a post but i cant figure out how to solve it, here is the output of the program:

---------------------------------------
El promedio del 20/09/2022 es: 200.0 °C

---------------------------------------
El promedio del 21/09/2022 es: 200.0 °C

---------------------------------------
El promedio del 22/09/2022 es: 150.0 °C

---------------------------------------
El promedio del 23/09/2022 es: 210.0 °C

---------------------------------------
El promedio del 24/09/2022 es: 180.0 °C

---------------------------------------
El promedio del 25/09/2022 es: 215.0 °C

---------------------------------------
El promedio del 26/09/2022 es: 225.0 °C

---------------------------------------
El promedio del 27/09/2022 es: 230.0 °C

---------------------------------------
El promedio del 28/09/2022 es: 178.0 °C

---------------------------------------
El promedio del 29/09/2022 es: 170.8 °C

---------------------------------------
El promedio del 30/09/2022 es: 225.0 °C

---------------------------------------
El promedio del 01/10/2022 es: 187.0 °C

---------------------------------------
El promedio del 01/10/2022 es: 187.0 °C


Pulse una tecla cualquiera para salir...
  • 4
    [`feof()`](https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/feof?view=msvc-170) doesn't do what you think it does. It does not tell you are at the end of file, but when you attempted to read *beyond* the end of the file. Please see [Why is `while ( !feof (file) )` always wrong?](http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) – Weather Vane Oct 20 '22 at 17:52

0 Answers0