2.编写程序,将排序输出“stud_info.csv”文件
#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);
}
1、编写程序,打开名为“stud_info.csv”的文件读取数据,并将学生数据在屏幕上输出。
输出效果示例:
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>
int main(void)
{
FILE *infp;
int num;
char name[20];
int ret;
if((infp = fopen("stud_info.csv","r"))==NULL)
{ printf("Cannot open infile.c.\n");
exit(0);
}
while(1){
ret =fscanf(infp,"%d,%s",&num,name);
if(ret <2)
break;
printf("%d,%s\n",num,name);
}
fclose(infp);
}