读取文件创建单链表.c

# 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 查看详细步骤*/

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值