随机生成20个点,每按一下回车生成一个,写入文件后将其读出,并按x的值升序排序后输出
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 20
typedef struct point
{
int x;
int y;
}POINT;
void sort(POINT *point);
void print(POINT *point);
int main(){
srand(time(NULL));
FILE *fp;
POINT point[N];
int i;
if((fp=fopen("points.txt","w"))==NULL){
printf("文件打开失败!\n");
exit(1);
}
for(i=0;i<N && getchar()=='\n';i++){
point[i].x=rand()%101;
point[i].y=rand()%101;
fprintf(fp,"(%d,%d)\n",point[i].x,point[i].y);
}
fclose(fp);
if((fp=fopen("points.txt","r"))==NULL){
printf("文件打开失败!\n");
exit(1);
}
i=0;
while( fscanf(fp,"(%d,%d)\n",&point[i].x,&point[i].y)==2){
printf("(%d,%d)\n",point[i].x,point[i].y);
i++;
}
sort(point);
printf("\n");
print(point);
fclose(fp);
}
void sort(POINT *point){
int i,j,k;
POINT temp;
for(i=0;i<N-1;i++){
k=i;
for(j=i+1;j<N;j++){
if(point[j].x < point[k].x){
k=j;
}
}
if(k!=i){
temp=point[i];
point[i]=point[k];
point[k]=temp;
}
}
}
void print(POINT *point){
int i;
for(i=0;i<N;i++){
printf("(%d,%d)\n",point[i].x,point[i].y);
}
}