Untitled

 avatar
unknown
plain_text
2 years ago
1.1 kB
4
Indexable
#include <stdio.h>

typedef struct {
    char name[20];
    char surname[20];
    int age;
}Persona;

int main() {

    FILE* fbin;
    Persona p;
    Persona p2;

    fbin = fopen("alexandra.dat", "wb");

    if (fbin == NULL) {
        printf("Error opening file");
        return 1;
    } else {

        for(int i = 0; i < 3; i++) {
            printf("Name: ");
            scanf("%s", p.name);
            printf("Surname: ");
            scanf("%s", p.surname);
            printf("Age: ");
            scanf("%d", &p.age);

            fwrite(&p, sizeof(Persona), 1, fbin);
        }

        fclose(fbin);

    }

    fbin = fopen("alexandra.dat", "rb");

    if(fbin == NULL) {
        printf("Error opening file");
        return 1;
    } else {

        fseek(fbin, sizeof(Persona)*2, SEEK_SET);
        //fseek(fbin, sizeof(Persona)*(-1), SEEK_END);
        //fseek(fbin, sizeof(Persona)*1, SEEK_CUR);

        fread(&p2, sizeof(Persona), 1, fbin);

        printf("\n\nName: %s", p2.name);
        printf("\nSurname: %s", p2.surname);
        printf("\nAge: %d", p2.age);

    }



    return 0;
}
Editor is loading...