2、在第一题的基础上,将这些数据按照学号升序进行排序,排序结果写入“stud_info2.csv”文件中,用excel开启表格文件,观察结果是否正确。
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>
#define N 100
struct student{
int num;
char name[20];
};
void swap_student(struct student *a, struct student *b)
{
struct student tmp;
tmp=*a;
*a=*b;
*b=tmp;
}
void sort_soap(struct student list[],int len)
{
int i, j;
for(j=0;j<len-1;j++){
for(i=0;i<len-j-1;i++){
if(list[i].num>list[i+1].num){
swap_student(&list[i],&list[i+1]);
}
}
}
}
void main(void)
{
int i;
struct student list[N]={0};
int ret;
int n;
FILE *infp,*outfp;
char ch;
if((infp=fopen("stud_info.csv","r"))==NULL){
printf("Cannot open infile.c.\n");
exit(0);
}
for(i=0;i<N;i++){
ret=fscanf(infp, "%d,%s",&list[i].num, &list[i].name);
if (ret<2)
break;
}
n=i;
sort_soap(list, n);
if((outfp=fopen("stud_info2.csv","w"))==NULL){
printf("Cannot open outfile.c.\n");
exit(0);
}
for(i=0;i<n;++i){
fprintf(outfp, "%d, %s\n",list[i].num, list[i].name);
}
fclose(infp);
fclose(outfp);
}