C 通过文本文件读取和显示链接列表
我正在尝试读取链接列表中的文本文件并成功显示它。但是我一直得到对应于(head==NULL)的“List is Empty”消息,同时我可以通过在read函数中使用put(id->…)参数成功地读取并打印文件一次,但是我无法访问上面提到的display函数C 通过文本文件读取和显示链接列表,c,pointers,linked-list,fopen,C,Pointers,Linked List,Fopen,我正在尝试读取链接列表中的文本文件并成功显示它。但是我一直得到对应于(head==NULL)的“List is Empty”消息,同时我可以通过在read函数中使用put(id->…)参数成功地读取并打印文件一次,但是我无法访问上面提到的display函数 struct node { char name[50]; int id; struct node *next; } *head; int main()
struct node
{
char name[50];
int id;
struct node *next;
} *head;
int main()
{
int i,num;
struct node *r;
head=NULL;
readfile(*r);
while (1)
{
printf("\nList Operations\n");
printf("============\n");
printf("1.Insert\n");
printf("2.Display\n");
printf("3.Delete by ID\n");
printf("4.Delete by Name\n");
printf("5.Exit\n");
printf("Enter your choice: ");
if (scanf("%d", &i) <= 0){
printf("Enter only an integer\n");
exit(0);
} else {
switch(i)
{
case 1:
if(head==NULL)
{
printf("List is Empty\n");
}
else
{
printf("Element in the list are: ");
}
display(r);
break;
case 2:
return 0;
default:
printf("Invalid Choice\n");
}
}
}
void readfile(struct node *r)
{
r=head;
char str[50];
int id;
FILE *ifp=fopen("One.txt","r");
while (fgets(str,50,ifp)!=NULL){
r =(struct node *)malloc(sizeof(struct node));
char *token=strtok(str,",");
strcpy(r->name,token);
puts(r->name);
token=strtok(NULL,"\n");
r->id=token;
puts(r->id);
r->next=NULL;
r=r->next;
}
}
void display(struct node *r)
{
r = head;
if(r == NULL)
{
return;
}
while(r != NULL)
{
printf("Student %s has id %d.\n", r->name,r->id);
r = r->next;
}
printf("\n");
}
struct节点
{
字符名[50];
int-id;
结构节点*下一步;
}*团长;
int main()
{
int i,num;
结构节点*r;
head=NULL;
读取文件(*r);
而(1)
{
printf(“\n列出操作\n”);
printf(“======================\n”);
printf(“1.插入\n”);
printf(“2.显示\n”);
printf(“3.deletbyid\n”);
printf(“4.按名称删除\n”);
printf(“5.退出\n”);
printf(“输入您的选择:”);
if(scanf(“%d”,&i)名称、令牌);
放置(r->name);
令牌=strtok(空,“\n”);
r->id=token;
put(r->id);
r->next=NULL;
r=r->next;
}
}
无效显示(结构节点*r)
{
r=头部;
if(r==NULL)
{
回来
}
while(r!=NULL)
{
printf(“学生%s的id为%d。\n”,r->name,r->id);
r=r->next;
}
printf(“\n”);
}
在您提供的代码中,您从未向标题分配或分配任何内容。我想你需要在下面的某个地方添加代码
if (head == NULL) {
head = r;
}
或
另外,我建议您创建更通用的函数,如add\u node
,如下所示
void add_node( struct node *r ) {
if(head == NULL) {
head = r;
} else {
struct node* n = head;
while(n->next != NULL) { // go to the end of the list
}
r->next = NULL; // to be sure this will be end of list
n->next = r;
}
}
然后在readfile
中读取数据,创建新节点并将其传递给add_node
void add_node( struct node *r ) {
if(head == NULL) {
head = r;
} else {
struct node* n = head;
while(n->next != NULL) { // go to the end of the list
}
r->next = NULL; // to be sure this will be end of list
n->next = r;
}
}