struct chexinxi *addchexinxi() { char str[]="0"; struct chexinxi *p,*pr; struct chexinxi *head; pr=p=(struct chexinxi *)malloc(sizeof(struct chexinxi)); printf("\t\t\t\t请输入以下内容(车牌号或车型号为0时退出):\n"); printf("\t\t\t\t车型号:"); scanf("%s",p->chexinghao); printf("\t\t\t\t车牌号:"); scanf("%s",p->chepaihao); printf("\n"); FILE *fp = fopen("data.txt", "w"); if(fp==NULL) { printf("\t\t\t\t打开文件失败!\n"); exit(1); } head=NULL; while(1) { if(strcmp(p->chexinghao,str)!=0&&strcmp(p->chepaihao,str)!=0) { if(head==NULL) head=p; else { pr->next=p; pr=p; } p=(struct chexinxi *)malloc(sizeof(struct chexinxi)); fprintf(fp, "%s %s\n", pr->chexinghao, pr->chepaihao); printf("\t\t\t\t车型号:"); scanf("%s",p->chexinghao); printf("\t\t\t\t车牌号:"); scanf("%s",p->chepaihao); printf("\n"); } else break; } pr->next=NULL; return head; } void xianshi(struct chexinxi *head) { struct chexinxi *p; p=head; if(head==NULL) { printf("无内容!"); } else { while(p!=NULL) { printf("\t\t\t\t车型号:%s 车牌号:%s\n",p->chexinghao,p->chepaihao); p=p->next; } } return; }优化显示内容从文件读入
时间: 2023-11-02 20:06:19 浏览: 31
首先,在函数`addchexinxi()`中,每次输入车型号和车牌号后,就立即将其写入文件中。这样会导致每次输入都要进行一次文件操作,影响效率。应该在输入完所有数据后再将其一次性写入文件中。
其次,在函数`xianshi()`中,可以从文件中读取车型号和车牌号,并且可以优化输出的格式,使其更加美观。
下面是修改后的代码:
```
struct chexinxi *addchexinxi() {
char str[]="0";
struct chexinxi *p,*pr;
struct chexinxi *head;
pr=p=(struct chexinxi *)malloc(sizeof(struct chexinxi));
printf("\t\t\t\t请输入以下内容(车牌号或车型号为0时退出):\n");
printf("\t\t\t\t车型号:");
scanf("%s",p->chexinghao);
printf("\t\t\t\t车牌号:");
scanf("%s",p->chepaihao);
printf("\n");
head=NULL;
while(1)
{
if(strcmp(p->chexinghao,str)!=0&&strcmp(p->chepaihao,str)!=0)
{
if(head==NULL)
head=p;
else
{
pr->next=p;
pr=p;
}
p=(struct chexinxi *)malloc(sizeof(struct chexinxi));
printf("\t\t\t\t车型号:");
scanf("%s",p->chexinghao);
printf("\t\t\t\t车牌号:");
scanf("%s",p->chepaihao);
printf("\n");
}
else
break;
}
pr->next=NULL;
// 将输入的内容写入文件
FILE *fp = fopen("data.txt", "a");
if(fp==NULL)
{
printf("\t\t\t\t打开文件失败!\n");
exit(1);
}
p = head;
while(p != NULL) {
fprintf(fp, "%s %s\n", p->chexinghao, p->chepaihao);
p = p->next;
}
fclose(fp);
return head;
}
void xianshi() {
FILE *fp = fopen("data.txt", "r");
if(fp==NULL) {
printf("\t\t\t\t打开文件失败!\n");
exit(1);
}
printf("\t\t\t\t车型号\t\t车牌号\n");
printf("\t\t\t\t------------------------\n");
char chexinghao[20], chepaihao[20];
while(fscanf(fp, "%s %s", chexinghao, chepaihao) != EOF) {
printf("\t\t\t\t%-15s\t%s\n", chexinghao, chepaihao);
}
fclose(fp);
}
```