大华一道C笔试题

题目大概是这样子的:

     请将文件in.txt的内容用fun函数实现排序生成out.txt文件。in.txt内的文件格式为:”姓名+空格+成绩+回车“

in.txt文件

张三    89
本四    34
王六    78
...
麻七    80
小八    99

生成的out.txt文件为

小八    99
张三    89
麻七    80
.....
王六    78
本四    34
请实现函数:int  fun(const char *fin,const char *fout);


解题思路:

    1.首先想到了将in.txt中的数据读取插入到链表中,所以我们必须定义一个数据结构;我们采用单链表的方式,在每个节点插入的过种中我们就对它排好序

      数据结构如下:

typedef struct Node
{
	char name[20];     //姓名
	int  sorce;              //成绩
	struct Node *next;//下一个节点指针
}NODE;

  2. 我们以面向对象的过程,来设计这个函数。

     将fun函数分解成三个子函数来实现

       

void ReadFile(const char *fin, NODE *head);    //读取文件
void WriteFile(const char *fout,const NODE *head);//向文件中写入数据
void InsertNode(NODE *head,const char* name, const int sorce);//向链表中插入结点

    2.1  ReadFile函数实现

void ReadFile(const char *fin, NODE *head)
{
	FILE *fp;
	fp=fopen(fin,"r");//以只读方式打开文件
	char str[20];
	int sroce;
	printf("read file start....\n");
	while(!feof(fp))//判断是否到达文件未尾
	{
	  fscanf(fp,"%s%d",&str,&sroce);
	  printf("%s %d \n",str,sroce);
	  InsertNode(head,str,sroce);
	}
	fclose(fp);
}

   2.2 WriteFile函数实现

void WriteFile(const char *fout,const NODE *head)
{
   FILE *fp;
   char str[40];
   NODE *p=head->next;
   fp=fopen(fout,"w+");//以读写的方式打开文件
   printf("write file start....\n");  
   while(NULL !=p)//此处使用p->next将会导致最后一个节点数据不打印出来
   {
	   sprintf(str,"%s %d\n",p->name,p->sorce);
	   printf("%s",str);
	   fputs(str,fp);
	   p=p->next;
   } 
   fclose(fp);
}

  2.3  InsertNode函数实现

void InsertNode( NODE *head,const char* name, const int sorce)
{
   NODE *pn,*p;
   p=head;
   pn=(NODE *)malloc(sizeof(NODE));
   strcpy(pn->name,name);
   pn->sorce=sorce;
   pn->next =NULL;
   //判定学生成绩按分数从高到低排序
   if(NULL==p->next)
   {//如果链表为空
	   p->next=pn;
   }else{
	   while(NULL !=p->next)
	   {
		   if(sorce>=(p->next)->sorce)
		   {
			   pn->next=p->next;
			   p->next = pn;
			   break;
		   }else{
	           p=p->next;
		   }
	   }
	   //如果到最后还未插入到链表中,则把节点插入到链表最后
	  if(NULL == p->next)
		  p->next=pn;
   }
}

  3. fun函数实现 

int  fun(const char *fin,const char *fout)
{
	NODE *head =(NODE *)malloc(sizeof(NODE));
	strcpy(head->name,"head");
	head->sorce=-1;
	head->next = NULL;
	ReadFile(fin,head);
	WriteFile(fout,head);
	free(head);
	return 0;
}

实现Demo,Main函数

int main(int argc,char* argv[])
{	
	fun("c:/a.txt","c:/out.txt");
	printf("over……\n");
	getchar();
	return 0;
}
程序运行结果如下:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值