C将Linked List写入文件

时间:2017-03-30 05:51:20

标签: c linked-list

我正在尝试将链接列表写入文件。添加新元素时遇到问题。 主要问题是在将结构(从文件读取)分配给new_node->next_node时,只将指针保存到new_node->next_node中。 在我从文件中读取后,尝试打印然后第一个结构值打印得很好,然后第二个值(node_trx->next_node)打印错误。我需要存储值而不是指向node_trx->next_node的指针。 那么有谁能说出我错了什么?

这是我的结构:

typedef struct {
    char amount[12];
    int currency;
    struct node_trx * next_node;
} node_trx;

这是添加新的元素代码:

 node_trx * trx_list;
 if (3 != read_last_trx_from_file(EMVP_LAST_TRANSACTION_OBJECT, &trx_list, &data_set_len)) {
    if (NULL == (f = fopen(tools_get_full_filename_const(EMVP_LAST_TRANSACTION_OBJECT), "w+"))) {
        log_ntrx_error(-1, "Cannot open ticket data set file: %s.",
                strerror(errno));
    } else {
        node_trx * new_node = calloc(1, sizeof(node_trx));

        strcpy(new_node->amount, disp_amount);

        new_node->currency = currency_code;

        memcpy(&new_node->next_node, &trx_list, sizeof trx_list);

        if (1 != fwrite(new_node, data_set_len + sizeof(node_trx), 1, f)) {
            //error
        }

        free(new_node);
        free(trx_list);
        fclose(f);
    }
} else {
    // Saving first element
    if (NULL == (f = fopen(tools_get_full_filename_const(EMVP_LAST_TRANSACTION_OBJECT), "w")))
    {
        log_ntrx_error(-1, "Cannot open ticket data set file: %s.",
                strerror(errno));
    } else {
        trx_list = BKS_XCALLOC(1, sizeof(node_trx));

        strcpy(trx_list->amount, disp_amount);

        trx_list->currency = currency_code;
        trx_list->next_node = NULL;

        if (1 != fwrite(trx_list, sizeof(node_trx), 1, f)) {

        }

        fclose(f);
    }

这是文件阅读功能:

int read_last_trx_from_file (const char * file_name, node_trx * * trx, unsigned * trx_len)
{
    FILE * f;
    *trx = NULL;

    if (NULL == (f = fopen(tools_get_full_filename_const(file_name), "rb")))
    {

    }

    size_t fsize;
    fseek(f, 0, SEEK_END);
    fsize = ftell(f);
    fprintf(stdout, "file size: %zd\n", fsize);
    if (!fsize)
    {
        return 3; // No data
    } else {
        if (fsize == 1) {
            return 3; // No data
        }
    }

    rewind(f);
    if (NULL != (*trx = (node_trx *) BKS_XCALLOC(1, fsize)))
    {
        if (1 != fread(*trx, fsize, 1, f))
        {
            fclose(f);
            return 2;
        }
    }
    fclose(f);

    *trx_len = fsize;
    return 0;
}

以下是我从文件代码中打印的数据:

 node_trx * card_data;
 if (3 != read_last_trx_from_file(LAST_TRX_OBJECT, &card_data, &data_set_len)) {
 while (card_data->next_node != NULL) {
     strcpy(amount, card_data->amount);
     printf("%s AMOUNT \n", amount);
     printf("%d CURRENCY \n", card_data->currency);
     card_data = card_data->next_node;
 }
}

1 个答案:

答案 0 :(得分:0)

如果链表是连续的,您可以按顺序存储元素。