Jump to content

Só guarda struct em ficheiro na segunda execução


Miguel_1

Recommended Posts

Boa tarde, eu estou a tentar gravar umas informações extras numa struct, por exemplo, o numero de vezes que uma empresa foi pesquisada e por onde, mas quando tento guardar num ficheiro na primeira vez não guarda, mas sim a partir da segunda execução.

As structs: 

typedef struct {
    int searchCounter, searchByNameCounter, searchByCategoryCounter, searchByActivityCounter;
} Information;

typedef struct {
    int maxInformation, numberInformation;
    Information *information;
} Informations;

e as funções de guardar e de dar load:

void updateStructInformation(char *txt, Informations *informations) {
    FILE *var = fopen(txt, "rb+");
    if (var == NULL) {
        perror("Erro ao abrir o arquivo");
        return;
    }
    fseek(var, 0, SEEK_SET);
    for (int i = 0; i < informations->numberInformation; ++i) {
        fwrite(&(informations->information[i]), sizeof(Information), 1, var);
    }
    fclose(var);
}
void loadStructInformation(int number, char *txt, Information *information, int structSize) {
    FILE *var = fopen(txt, "rb+");
    if (var == NULL) {
        var = fopen(txt, "wb");
        fclose(var);
        return;
    }
    fseek(var, 0, SEEK_SET);
    fread(information, structSize, number, var);
    fclose(var);
}

e eu inicio as informações da struct no main:

Informations informations = {
            .maxInformation = numberCompanies > 10 ? numberCompanies * 2 : 10,
            .numberInformation = numberCompanies,
            .information = (Information *)
                    malloc(informations.maxInformation * sizeof(Information))
    };

Agradeço toda a ajuda :)

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.