gpt4 book ai didi

C 编程、文件、链表

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

该程序将从文件中读取您的 friend ,并使用链接列表来存储您 friend 的详细信息。请注意,您不能对您的 friend 数量和数量做出任何假设好友数量没有上限。

这是我的代码,它不起作用。我用了strtok...

文件内容应为:

Name1; Surname1;M;01.06.1990;
Name2;Surname2;F;02.04.1992;

这是我的代码:

#include<stdio.h>

#include<stdlib.h>

#include<string.h>

struct Friend{
char *name;
char *sur;
char *gen;
char *date;
struct Friend *next;
};
struct Friend * initialize(char *);
void display(struct Friend *);
int main()
{
printf("\nsdasda\n");
struct Friend *head;
char fname[100];
printf("Enter the name of file .txt: \t");
gets(fname);
head=initialize(fname);
display(head);

}
struct Friend * initialize(char *fname){
FILE* fpointer;
char ch;
fpointer = fopen(fname,"r");
if(fpointer == NULL){

do
{
printf("\nFile not found, please enter the name of file again: \t");
gets(fname);
fpointer = fopen(fname,"r");
}while(fpointer == NULL);
}
//FILE IS OPENED
struct Friend *head=(struct Friend*)malloc(sizeof(struct Friend));
struct Friend *t;
t=head;
char line[255];
char sent[2]=";";

while(!feof(fpointer)){
fgets(line,sizeof line,fpointer);
t->name=strtok(line,sent);
t->sur=strtok(NULL,sent);
t->gen=strtok(NULL,sent);
t->date=strtok(NULL,sent);
if(!feof(fpointer)){
t->next=(struct Friend*)malloc(sizeof(struct Friend));
t=t->next;
}
else if(feof(fpointer)){

t->next=NULL;

}

}

return head;

};

void display(struct Friend *head){
puts(head->name);
}

最佳答案

这里有很多问题,不确定是否详尽:

  • gets 不安全,切勿使用。了解如何使用 fgets,这是一种更安全的替代方案
  • while(!feof(fpointer)) 几乎总是错误的。读取最后一行后,feof 仍然为 false,只有在第一次不成功的读取操作后才会为 true。因此文件结束的测试必须在数据读取和处理之间进行。
  • 不要在 C 中强制转换 malloc!它没有用,只能在出现间接级别错误时隐藏编译器警告
  • 永远、永远不要在可重复使用的字符串中分配字符指针。您只存储一个地址并在下次读取时删除内容。为每个新字符串分配内存或使用 strdup 在幕后执行此操作(顺便说一句,这可能是导致您的程序无法工作的原因)。
  • 始终释放您分配的内容,无论是使用 strdupmalloc 还是内部使用 malloc 的任何其他函数
  • 始终从 main 向环境返回一个合理的值。真正的程序不是从 IDE 运行的...

关于C 编程、文件、链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47266960/

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