/*Write a program that reads the a.txt file, sorts the file content numbers from small to large, and writes the sorted results to b.txt. */#include<stdio.h>#include<stdlib.h>#include<string.h>#include<errno.h>//Insert SortvoidInertionsort (int* Arr,intLen) { if(arr==NULL) {printf ("the incoming parameter cannot be empty! \ n"); return; } intI=0, j=0, k=0, temp=0; for(i=1; i<len;i++) {k=i; Temp=Arr[k]; for(j=i-1; j>=0&&temp<arr[j];j--) {arr[j+1]=Arr[j]; K=J; } //the function of k is that it will not enter the loop when Temp>=arr[j], at which point J is the last element of the ordered array//arr[j]=temp; the last ordered element is covered by the//arr[j]=temp; Errorarr[k]=temp; }}intMainintArgChar*args[]) { if(arg<3) {printf ("This program requires two parameters! \ n"); return 0; } //define file StreamFILE *pfr=NULL; //Open the file in the Read modePfr=fopen (args[1],"R"); //Judge if(pfr==NULL) {printf ("read the file failed! Error msg:%s\n", Strerror (errno)); return 0; } //Create arr intindex=0; //here index is used as the length of the array, the initial value of index is 0, so the index will be more than 1 after the loop, just when index is the length of the array intarr[ -]={0}; Charbuf[Ten]={0}; while(Fscanf (PFR,"%s", buf)! =EOF) {Arr[index++]=atoi (BUF); memset (BUF,0,sizeof(BUF)); } //close the file stream if(PFR) {fclose (PFR); PFR=NULL; } inertionsort (Arr,index); //define new file streamFILE * pfw=NULL; //open new file in Append modePfw=fopen (args[2],"a"); if(pfw==NULL) {printf ("write the file failed! Error msg:%s\n", Strerror (errno)); return 0; } //Write the file intnum=0; while(num<index) {memset (buf,0,sizeof(BUF)); sprintf (BUF,"%d\n", arr[num++]); Fputs (BUF,PFW); } //close the file stream if(PFW) {fclose (PFW); PFW=NULL; } return 0;}
Linux Linux Program Exercise II