使用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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章