c 实现对文件操作:选择排序

分别实现选择排序和冒泡排序(在上上篇文章)对以下文件进行排序。
支持如下形式调用:BubbleSort.exe input.txt output.txt 0
                                    BubbleSort.exe input.txt output.txt 1
                                     (0:从小到大,1:从大到小)。
注意中文处理(若无法处理可以只对学号排序,需要在文档中说明)

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 #include<string.h>
 4 
 5 #define N 200
 6 struct student{
 7     char num[200];
 8     char name[200];
 9     float ave;
10 }st[N],temp1;
11 
12 struct Newstudent{
13     char num[200];
14     char name[200];
15     char row[200];
16     float ave;
17 }st_New[N],temp2;
18 
19 //void SelectionSort();
20 
21 
22 void main(int argc,char **argv){
23    FILE *fp1,*fp2;
24    int i,j,sum,min;
25    char str[200];
26    char *input,*output,flag;
27    char tempOne[200];
28    char tempTwo[200];
29    //char *str[N];
30 
31    if(argc<4){
32       input="input.txt";
33       output="output.txt";
34       flag='0';
35     }
36    else{
37       input=*(argv+1);
38       output=*(argv+2);
39       flag=**(argv+3);
40    }
41 
42    /*读文件*/
43    if((fp1=fopen("input.txt","r"))==NULL){
44        printf("can not open.");
45        exit(0);
46    }
47    sum=0;
48    printf("the File '算法设计点名册' is :\n");
49    
50    for(i=0;(fgets(str,200,fp1))!= NULL;i++,sum++) {
51        strcpy(st[i].num,strtok(str,","));
52        strcpy(st[i].name,strtok(NULL,","));
53        //printf("%s",st[i].num);
54        //printf("%s",st[i].name);
55    }
56    //printf("如果希望从小到大排列请输入0,如果希望从大到小排列请输入1:\n");
57    //scanf("%d",&flag);
58   /*选择排序*/
59    for(i=0;i<193;i++){
60         min=i;
61         for(j=i+1;j<194;j++)
62             if(flag){
63               if(strcmp(st[j].num,st[min].num)>0)
64                  min=j;
65             }
66             else{
67               if(strcmp(st[j].num,st[min].num)<0)
68                  min=j;
69             }
70         strcpy(tempOne,st[i].num);
71         strcpy(st[i].num,st[min].num);
72         strcpy(st[min].num,tempOne);//互换值
73         
74         strcpy(tempTwo,st[i].name);
75         strcpy(st[i].name,st[min].name);
76         strcpy(st[min].name,tempTwo);//互换值
77    }
78 
79    /*写入新文件*/
80    if((fp2=fopen("output.txt","wb"))==NULL){
81        printf("can not open.");
82        exit(0);
83    }
84    for(j=0;j<sum;j++){
85        strcpy(st_New[j].num,strcat(st[j].num,","));//得到学号和逗号
86        //printf("%s",st_New[j].num);
87        strcpy(st_New[j].name,strcat(st_New[j].num,st[j].name));//合并num和学生姓名
88        printf("%s",st_New[j].name);//输出排序后的点名册
89        fputs(st_New[j].name,fp2);
90    }
91 
92    /*关闭所有文件*/
93    fclose(fp1);
94    fclose(fp2);
95    /*NOUSe*/
96    scanf("%d",i);
97 }
原文地址:https://www.cnblogs.com/daomul/p/2726957.html