# include <stdio.h>
# include <stdlib.h>
FILE *fp ;
typedef struct student {
int id ;
int age ;
int score ;
char name[20];
struct student *next ;
}STU , *PSTU ;
PSTU head = NULL ;
int main ()
{
fp = fopen ("stu.txt","r");
if (fp == NULL){
printf ("打开文件失败") ;
return -1;
}
#ifdef DEBUG
printf ("step 1 open file\n");
sleep (1);
printf ("\n");
#endif
PSTU p ;
while(1){
p = malloc(sizeof (STU)) ;
#ifdef DEBUG
printf ("step 2 apply for space\n");
sleep(1);
printf ("\n");
#endif
int ret ;
ret = fscanf (fp ,
"%d%d%d%s",
&p->id,&p->age,&p->score,p->name ) ;
#ifdef DEBUG
printf ("step 3 fscanf file \n");
sleep(1);
printf ("\n");
#endif
if (ret <4 )
// return 0 ; return 为无条件结束整个函数,故需用break ;
break ;
if (head == NULL)
{ p->next = NULL ;
head = p ;
#ifdef DEBUG
printf ("step 4 create head node\n");
sleep(1);
printf ("\n");
#endif
}
else
{
p->next = head ;
head = p ;
#ifdef DEBUG
printf ("step 5 create body node\n");
sleep(1);
printf ("\n");
#endif
}
}//end while(1)
p = head ;
printf("学号\t年龄\t分数\t姓名\n");
while (p)
{
#ifdef DEBUG
printf ("step 6 printf node information\n");
sleep(1) ;
printf ("\n");
#endif
printf ("%d\t%d\t%d\t%s\n",p->id,p->age,p->score,p->name);
p = p->next ;
} //end while(p)
return 0 ;
}
/*编译时可用 gcc -DDEBUG -o *** ***.c 查看详细步骤*/