将链表的链表保存到二进制文件中

问题描述 投票:-1回答:1

我正在尝试创建一个二进制文件,其中只包含第一个数字(例如“123456789”)和以下文本文件中的名称:

123456789 0 Paulo Silva

555666777 2 Marta Nunes Cabral
1   1   12  12  2017    17  12  2017
2   0   20  04  2018

123123123 3 Maria Pimentel
2   2   01  10  2017    10  10  2017
2   1   13  01  2018    15  01  2018
1   0   17  04  2018

这是我到目前为止的代码:

void gravaClientesBanidos(pClientes cli){
    FILE *f;
    int total = 0;

    f = fopen("Banidos.dat", "wb");
    if(f == NULL)
        printf("Erro ao escrever o ficheiro");

    while(cli != NULL){
        if(cli->banido == true){
            fwrite(cli, sizeof(clientes), 1, f);
            cli = cli->prox;
            total++;
        }
    }

    fwrite(&total, sizeof(int), 1, f);
    fclose(f);
}

前提是如果客户端被禁止,它应该自动放入该二进制文件中。当我将它保存到二进制文件时,我相信它会保存第一行,但是当我尝试读取文件时它只会崩溃程序

这是读取代码:

void leClientesBanidos(){
    FILE *f;
    pClientes novo;
    int i, total;

    f = fopen("Banidos.dat", "rb");
    if(f == NULL)
        printf("Não existe dados para ler!");


    fseek(f, sizeof(int), SEEK_END);
    fread(&total, sizeof(int), 1, f);

    for(i = total - 1; i >= 0; i--){
        fseek(f, sizeof(clientes) * i, SEEK_SET);
        fread(novo, sizeof(clientes), 1, f);
    }
    printf("NIF: %d\nNome: %s", novo->NIF, novo->nome);
    fclose(f);
}

编辑:忘了把关于这个案子的结构

typedef struct Alugueres alugueres, *pAlugueres;
typedef struct Clientes clientes, *pClientes;

struct Alugueres{
    int ID;
    int estado; //0 - A decorrer, 1 - Entregue, 2 - Entregue Danificada
    data dataInicio;
    data dataFim;
    data dataEntrega;
    pAlugueres prox;
};

struct Clientes{
    char nome[25];
    int nAlugueres;
    int NIF;
    int razaoBanido; //0 - atraso, 1 - Guitarras danificadas, 2 - Nao ha razao
    bool banido; //0 - Nao, 1 - SIM
    int count; //Contagem das guitarras danificadas entregues
    pAlugueres al;
    pClientes prox;

};

更新:所以我认为我发现了问题,当我尝试读取“总”整数(这是存储在文件末尾的文件中的结构数)时,它只是用垃圾填充它而不是正确的数字。 ..但如果我手动将total = 3放入读取功能,它工作正常。

显然这不是我希望它工作的正确方法,有没有人对如何解决这个问题有意见?

c
1个回答
0
投票

qazxsw poi宣布未初始化的指针。你需要qazxsw poi

要在文件末尾附近阅读,请使用:

pClientes novo

请尝试以下方法。

clientes novo
© www.soinside.com 2019 - 2024. All rights reserved.