read from binary file to linked list c

Asked

Viewed 463 times

0

Good people, I’m having a problem reading information from a binary file to enter it in memory on a linked list.

PERGUNTAS val;

lista_perguntas * aux = original->next;
lista_perguntas * base = original;
lista_perguntas * novo;


 while (aux != NULL) {    // eu estava com um problema anteriormente que o primeiro elemento da lista era ignorado por isso eu pesquisei e encontrei esta solução que basicamente ignora esse elemento e passa para o segundo pelo que eu percebi
    aux = aux->next;
    base = base->next;
}


 while(fread(&val, sizeof(PERGUNTAS), 1, fp)!=-1){

novo = (lista_perguntas*) malloc(sizeof (lista_perguntas));
novo->valor = val;
novo->next = aux;
base->next = novo;

 }

My goal would be to read the file information at a time and insert it into a new node of the list only the program is giving error. I don’t quite know this list yet so I’d appreciate it if you could enlighten me :).

Thank you

1 answer

1

Here’s an example that might solve your problem:

Data structure:

#define PERGUNTA_TAM_MAX   (256)

typedef struct pergunta_s pergunta_t;

struct pergunta_s
{
    char pergunta[ PERGUNTA_TAM_MAX + 1 ];
    pergunta_t * prox;
};

Function to load a list of questions from a file:

int perguntas_carregar( const char * arq, pergunta_t ** perg )
{
    FILE * pf = NULL;
    pergunta_t * p = NULL;
    pergunta_t * pant = NULL;
    pergunta_t * pprim = NULL;
    int n = 0;
    int nread = 0;

    pf = fopen( arq, "rb" );

    if(!pf)
        return ERRO_LEITURA_ARQUIVO;

    while(1)
    {
        p = malloc( sizeof(pergunta_t) );

        nread = fread( p, sizeof(pergunta_t), 1, pf );

        if( nread != 1 )
        {
            free(p);
            break;
        }

        p->prox = NULL;

        if(pant)
            pant->prox = p;
        else
            pprim = p;

        pant = p;

        n++;
    }

    fclose(pf);

    *perg = pprim;

    return n;
}

I hope I’ve helped!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.