使用qsort对结构体指针数组根据compare规则进行排序

有一个记录学生信息的文件,每一行记录一名学生的信息,格式如下:
学号\t 姓名\t 性别\t 分数 1\t 分数 2\t 分数 3\n.
要求:
(1) 读取文件的内容, 串成一个链表。
(2) 按照总分递减排序将结果保存到原文件
(3)使用命令行参数读取文件

#define _CRT_SECURE_NO_WARNINGS
#define USR_NAME_LEN 20
#define N 10
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct student
{
	int usr_id;
	char usr_name[USR_NAME_LEN];
	int gender;
	double course_score_1;
	double course_score_2;
	double course_score_3;
	struct student* pNext;
}Student_t, *pStudent_t;
int compare(const void* p1, const void* p2)
{
	pStudent_t* ptr1 = (pStudent_t*)p1;
	pStudent_t* ptr2 = (pStudent_t*)p2;
	if (((*ptr1)->course_score_1 + (*ptr1)->course_score_2 + (*ptr1)->course_score_3) >((*ptr2)->course_score_1 + (*ptr2)->course_score_2 + (*ptr2)->course_score_3))
	{
		return 1;
	}
	else
	{
		return 0;
	}
}
int main(int argc, char** argv)
{
	FILE* fp;
	pStudent_t phead = NULL;
	int cnt = 0;
	if (argc != 2)
	{
		printf("error args\n");
		return -1;
		system("pause");
	}
	fp = fopen(argv[1], "r+");
	if (NULL == fp)
	{
		perror("fopen");
		return -1;
	}
	pStudent_t tmp = (pStudent_t)calloc(1, sizeof(Student_t));
	while ((fscanf(fp, "%d\t%s\t%d\t%lf\t%lf\t%lf\n", &tmp->usr_id, tmp->usr_name,&tmp->gender,&tmp->course_score_1, &tmp->course_score_2, &tmp->course_score_3)) == 6)
	{
		pStudent_t pnew = (pStudent_t)calloc(1, sizeof(Student_t));
		pnew->usr_id = tmp->usr_id;
		strcpy(pnew->usr_name, tmp->usr_name);
		pnew->gender = tmp->gender;
		pnew->course_score_1 = tmp->course_score_1;
		pnew->course_score_2 = tmp->course_score_2;
		pnew->course_score_3 = tmp->course_score_3;
	if (phead == NULL)
	{
		phead = pnew;
	}
	else
	{
		pStudent_t ppreNode = phead;
		pStudent_t pcurNode = phead;
	while (pcurNode)
	{
		ppreNode = pcurNode;
		pcurNode = pcurNode->pNext;
	}
	ppreNode->pNext = pnew;
	pnew->pNext = NULL;
	}
		cnt++;
	}
	fclose(fp);
	pStudent_t* pArr = (pStudent_t*)calloc(cnt, sizeof(pStudent_t));
	pStudent_t pCur = phead;
	for (int i = 0; i < cnt; i++)
	{
		pArr[i] = pCur;
		pCur = pCur->pNext;
	}
	pCur = NULL;
	qsort(pArr, cnt, sizeof(pStudent_t), compare);
	fp = fopen(argv[1], "w+");
	if (NULL == fp)
	{
		perror("fopen");
		return -1;
	}
	for (int i = 0; i < cnt; i++)
	{
		fprintf(fp, "%d\t%s\t%d\t%f\t%f\t%f\n", pArr[i]->usr_id, pArr[i]->usr_name, pArr[i]->gender,pArr[i]->course_score_1, pArr[i]->course_score_2, pArr[i]->course_score_3);
	}
	fclose(fp);
	while (phead != NULL)
	{
		pCur = phead;
		phead = phead->pNext;
		free(pCur);
		pCur = NULL;
	}
	free(pArr);
	system("pause");
	return 0;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值