Question

In the code posted below, there is problem when writing and reading a structure from a file. The output result is garbage data, I wasn't able to find a solution on my own. Operating system used: Ubuntu.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef struct eventos {
    int id;
    char titl[60];
    char desc[120];
    int estado;
} evento;

struct eventos y;

void nuevo_evento(struct eventos *event){
    FILE *eve;
    eve = fopen("Eventos.dat","ab+");
    fwrite(&event,sizeof(struct eventos),1,eve);
    fclose(eve);
}

void VerEventos(){
    FILE *events2 = fopen("Eventos.dat", "rb+");
    printf("------------------------------\n");
    fread(&y, sizeof(struct eventos), 1, events2);
    while(!feof(events2)){
        printf("%d      %s      %d      %s\n", y.id, y.titl, y.estado, y.desc);
        fread(&y, sizeof(struct eventos), 1, events2);
    }
    printf("------------------------------\n");
    fclose(events2);
}

int main(){
    remove("Eventos.dat");

    y.id = 1;
    y.estado = 0;
    strcpy(y.titl,"Evento1");
    strcpy(y.desc,"evento culiao");

    nuevo_evento(&y);

    y.id = 2;
    y.estado = 0;
    strcpy(y.titl,"Evento2");
    strcpy(y.desc,"evento bacan");

    nuevo_evento(&y);

    VerEventos();

    return 0;
}
Était-ce utile?

La solution

In the function nuevo_evento() , of the latest program you posted, just change

fwrite(&event,sizeof(struct eventos),1,eve);

to

fwrite(event,sizeof(struct eventos),1,eve);

If you look at, the fwrite() function , the first parameter is the pointer to the data. In your program , &event is the address of the pointer itself , but event is the address of the structure it is pointing to , and that is what you have to use with fwrite().

Also have a look at this question , it will be of help to the problem you are facing.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top