gpt4 book ai didi

C 将链表写入文件

转载 作者:行者123 更新时间:2023-11-30 16:48:06 25 4
gpt4 key购买 nike

我正在尝试将链接列表写入文件。添加新元素时遇到问题。主要问题是当将结构体(从文件读取)分配给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;
}
}

最佳答案

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

关于C 将链表写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43109541/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com