I have two binary files made in C , one to write and one to read, when executing the write program I think it's all right and I save it in the file, but when executing the reading I get symbols and rare characters ..
Here the code of both:
Writing
struct datos_alumnos{
int matricula;
char nombre[30];
int edad;
}alumnos[2];
int main()
{
FILE *fichero;
fichero = fopen("alumnos.dat","wb");
if(fichero == NULL)
{
printf("Error, el fichero no se puede abrir");
}
printf("Introduzca los datos del alumno que desee dar de alta\n\n");
for(int i=0;i<2;i++)
{
fflush(stdin);
printf("Nombre del %d%c alumno: ",i+1,167);
gets(alumnos[i].nombre);
printf("Su N%c de matricula: ",167);
scanf("%d",&alumnos[i].matricula);
printf("Su edad: ");
scanf("%d",&alumnos[i].edad);
printf("\n");
fwrite(alumnos,sizeof(struct datos_alumnos),1,fichero);
}
if(fichero != NULL)
{
printf("\n\n DATOS GUARDADOS CORRECTAMENTE");
}
fclose(fichero);
return 0;
Reading
int main()
{
FILE *fichero;
fichero = fopen("alumnos.dat","rb");
if(fichero == NULL)
{
printf("Error, no se pudo leer el fichero");
}
while(!feof(fichero))
{
for(int i=0;i<2;i++)
{
fread(&alumnos[i],sizeof(struct datos_alumnos),1,fichero);
printf("%s\n",alumnos[i]);
}
}
fclose(fichero);
return 0;