#include<stdio.h>#include<stdlib.h>typedef struct clothes{ char num[20]; char name[20]; char time[30]; float price; int number; struct clothes *next;}CLO;int main() { FILE *fp1; CLO *d,*c,*head; head=0; if((fp1=fopen("D:\handclothes.txt","r"))==NULL) { printf("Failure to open clothes.txt!\n"); exit(0); } while(!feof(fp1)) { if((c=(CLO *)malloc(sizeof(CLO)))==NULL) { printf("Not able to allocate memory.\n"); exit(1); } fscanf(fp1,"%s",c->num); fscanf(fp1,"%s",c->name); fscanf(fp1,"%s",c->time); fscanf(fp1,"%f",&c->price); fscanf(fp1,"%d",&c->number); if(head==0) { head=c; d=c; } else { d->next=c; d=c; } } d->next=0; fclose(fp1); printf("%d",head->number); free(head); return 0;}
用代码块格式化一下啊,这怎么看
内存要加1
#include<stdio.h>
#include<stdlib.h>
typedef struct clothes
{ char num[20];
char name[20];
char time[30];
float price;
int number;
struct clothes *next;
} CLO;
int main() {
FILE *fp1;
CLO *d,*c,*head;
head=0;
if((fp1=fopen("D:\handclothes.txt","r"))==NULL)
{ printf("Failure to open clothes.txt!\n");
exit(0);
}
while(!feof(fp1))
{ if((c=(CLO *)malloc(sizeof(CLO)+1))==NULL)
{ printf("Not able to allocate memory.\n");
exit(1);
}
fscanf(fp1,"%s",c->num);
fscanf(fp1,"%s",c->name);
fscanf(fp1,"%s",c->time);
fscanf(fp1,"%f",&c->price);
fscanf(fp1,"%d",&c->number);
if(head==0) {
head=c;
d=c;
}
else {
d->next=c;
d=c;
}
}
d->next=0;
fclose(fp1);
printf("%d",head->number);
free(head);
return 0;
}