gpt4 book ai didi

c - 将结构保存在文件中

转载 作者:行者123 更新时间:2023-11-30 20:56:34 24 4
gpt4 key购买 nike

我正在编写一个程序,将联系人列表保存在文件结构中。我已经尝试了很多方法,但是当我尝试将文件读取到程序时,它没有读取任何内容。

这是我的程序,没有打开文件并保存到文件:

#include <stdio.h>
#include <stdlib.h>

struct agenda {
int idContacte;
char name[50];
struct agenda *nextContacte;
};
struct agenda *pAgenda;
struct agenda *pFirst = NULL;
struct agenda *pIndex;

void insert();
void show();

int main()
{
//Menu
int opc;
while(1){
printf("1.Insert Contact.\n");
printf("2.Show Contacts.\n");
printf("3.Exit\n");
scanf("%d", &opc);
switch(opc){
case 1:
insert();
break;
case 2:
show();
break;
case 3:
return 0;
}
}
}
void insert(){
pAgenda = (struct agenda *)malloc(sizeof(struct agenda));
printf("Insert ID: ");
scanf("%d", &pAgenda->idContacte);
printf("Insert the name: ");
scanf("%s", pAgenda->name);
printf("\n");
if (pFirst==NULL || pAgenda->idContacte < pFirst->idContacte)
{
pAgenda->nextContacte=pFirst;
pFirst=pAgenda;
}
else if (pAgenda->idContacte > pFirst->idContacte){
pIndex=pFirst;
while(pIndex->nextContacte && pIndex->nextContacte->idContacte < pAgenda->idContacte)
{
pIndex = pIndex->nextContacte;
}
pAgenda->nextContacte = pIndex->nextContacte;
pIndex->nextContacte = pAgenda;
}
}
void show(){
pIndex = pFirst;
while(pIndex && pIndex->idContacte <= 100) {
printf("\nID: %d", pIndex->idContacte);
printf("\nNAME: %s", pIndex->name);
printf("\n\n");
pIndex = pIndex->nextContacte;
}
}

你能帮助我如何在程序启动时从文件中获取联系人,然后在插入联系人时重写文件并在文件中再次插入所有联系人吗?

最佳答案

当你结束程序时,你应该执行以下操作

int save_list(struct agenda *head) {
FILE *save = fopen("file.name", "wb");
if(!save) return -1;

while(head) {
fwrite(head, sizeof *head - sizeof head, 1, save);
head = head->nextContacte;
}

fclose(save);
/* Somebody would free list memory after this function execution */
return 0;
}

在程序开始时,您应该执行以下操作

struct agenda *restore_list() {
FILE *restore= fopen("file.name", "rb");
struct agenda *head = NULL;
struct agenda *cur = head;
struct agenda temp;
if(!restore) return head;

while( fwrite(&temp, sizeof temp - sizeof head, 1, save) == 1) {
struct agenda *node = malloc( sizeof(struct agenda) );
if(NULL == node) {
/* Handle out of memory error here, free list */
return NULL;
}
*node = temp;
node->nextContacte = NULL;
if(head) {
cur->nextContacte = node;
cur = node;
} else {
/* First node */
head = cur = node;
}
}

fclose(restore);
return head;
}

关于c - 将结构保存在文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23844566/

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