IO.cRUN

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>

/*
创建一个文本文件a.txt,第一行输入你宿舍人数,第二行开始,按学号依次输入你宿舍所有同学的信息。包括姓名,学号,电话号码,以及年龄。之间用空格隔开。
编写程序。
a) 定义结构体,读入文件a.txt,保存到动态结构体数组中。
b) 按照年龄对宿舍同学排序,如果年龄相同,则根据电话号码排序。
*/


//姓名,学号,电话号码,以及年龄
struct Student {
	char name[32];
	int id;
	int phone;
	int age;
};


//比较
int Compare(const struct Student* s1, const struct Student* s2)
{
	if (s1->age > s2->age)return 0;
	if (s1->phone > s2->phone)return 0;
	return 1;
}


struct Student* Input(const char *in, int *pn)
{
	FILE* fp = fopen(in, "rt");
	fscanf_s(fp, "%d", pn);
	struct Student* students = (struct Student*)malloc(sizeof(struct Student) * (*pn));
	fclose(fp);

	for (int i = 0; i < *pn; i++)
	{
		fscanf_s(fp, "%s", students[i].name, 32);
		fscanf_s(fp, "%d", &students[i].id);
		fscanf_s(fp, "%d", &students[i].phone);
		fscanf_s(fp, "%d", &students[i].age);
	}

	return students;
}


//冒泡排序
void Sort(struct Student* students, int n)
{
	for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < n - i - 1; j++)
		{
			if (Compare(&students[j], &students[j + 1]))
			{
				struct Student tmp = students[j];
				students[j] = students[j + 1];
				students[j + 1] = tmp;
			}
		}
	}
}


void Output(const char *outfile, const struct Student* students, int n)
{
	//输出
	FILE* fp = fopen(outfile, "w+t");
	fprintf(fp, "%d", n);
	for (int i = 0; i < n; i++)
	{
		fprintf(fp, "%s", students[i].name);
		fprintf(fp, "%d", students[i].id);
		fprintf(fp, "%d", students[i].phone);
		fprintf(fp, "%d", students[i].age);
	}
	fclose(fp);
}


int main()
{
	int number = 0;
	struct Student* students = Input("in.txt", &number);
	Sort(students, number);
	Output("out.txt", students, number);
	free(students);

	return 0;
}