我倒是想出来一个办法,也不知道对不对,在此献丑了。要把文件存为 tmp.c ,然后读入文件,存入数据,再对此排列
程序代码:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define N 5
#define CHAR_END 100
void sort();
int cmp(const void *a, const void *b)
{
return *(int *)b - *(int *)a;
}
int main(void)
{
int num[N] = { 4, 2, 15, 1, 11 };
sort();
return 0;
}
void sort()
{
char ch[CHAR_END];
char *s = ch;
int a[N];
int i, j;
FILE *fp;
while ((fp = fopen("tmp.c", "r")) == NULL) ;
while (!feof(fp))
{
fgets((char *)s, CHAR_END, fp);
if (!strncmp(s, " int num", 6))
{
break;
}
}
while (*s < '0' || *s > '9')
{
s++;
}
for (i = 0; i < N; ++i)
{
a[i] = 0;
}
for (i = 0; i < N; )
{
if (*s >= '0' && *s <= '9')
{
a[i] = a[i] * 10 + *s - '0';
s++;
}
else
{
++i;
while(*s<'0'||*s>'9')
{
s++;
}
}
}
qsort(a, N, sizeof(a[0]), cmp);
for (i = 0; i < N; ++i)
{
printf("%3d", a[i]);
}
puts("");
fclose(fp);
}