I have, I'm trying to read a binary file until end and print the result, I'm using and while with "feof" to read until end of file and printing each result, but I have a problem it is giving me double end result.
I'm still learning C, so I don't know why its giving me double end result, I have tried so many ways, but this was for me the best way and easiest that at least works, but now I'm stuck after 2 hours trying to fix it.
Result:
0
1
2
3
4
5
6
7
8
9
9
Expected:
0
1
2
3
4
5
6
7
8
9
My code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
// https://www.aprendeaprogramar.com/cursos/verApartado.php?id=16007
struct Datos
{
int cero;
int uno;
int dos;
int tres;
int cuatro;
int cinco;
int seis;
int siete;
int ocho;
int nueve;
};
struct Datos datosEscrito = {0,1,2,3,4,5,6,7,8,9};
FILE *fichero;
fichero = fopen("tabla2.dat", "wb");
fwrite(&datosEscrito, sizeof(datosEscrito), 1, fichero);
fclose(fichero);
int datoLeido;
FILE *fichero2;
fichero2 = fopen("tabla2.dat", "rb");
while (!feof(fichero2))
{
fread(&datoLeido, sizeof(datoLeido), 1, fichero2);
printf("%u", datoLeido);
printf("\n");
}
fclose(fichero2);
}
PD: I don't want the code fix, I want to understand why is giving me double end and an approach to fix the error myself, or another way to do the same. Thanks for the help.
Code edit:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
FILE *fichero;
fichero = fopen("tabla2.dat", "wb");
int count=0;
while (count != 10)
{
fwrite(&count, sizeof(count), 1, fichero);
count++;
}
fclose(fichero);
// PARTE LEER
int datoLeido;
FILE *fichero2;
fichero2 = fopen("tabla2.dat", "rb");
while (!feof(fichero2))
{
fread(&datoLeido, sizeof(datoLeido), 1, fichero2);
printf("%u", datoLeido);
printf("\n");
}
fclose(fichero2);
return 0;
}