Help with these binary files in C

0

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;
    
asked by Mario Guiber 01.08.2017 в 11:56
source

1 answer

2

At first glance, the main suspect would be:

printf("%s\n",alumnos[i]);

alumnos[i] is not a string / char [], it is a structure; and the first element of this structure is a int 1 . It should be something like:

printf("%d %d %s\n", i+1, alumnos[i].matricula, alumnos[i].nombre);

The rest of the code seems correct at first glance. If there are still problems, the points to check would be:

  • In the first program, print on the screen the content of the structure (for example, with the line I have put myself) to rule out an error there.

  • Open the file with some basic text editor (Notepad or similar), some symbols will be rare (those corresponding to the numerical data) but the name should be clearly visible.

  • Print the sizeof value of the struct and make sure the file size is 2 * sizeof.

1 If the first element were char[] , in certain architectures it could work.

    
answered by 01.08.2017 / 12:19
source