C程序使用标准库函数qsort排序整数文件
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#define MAX 10
int int_cmp(const void *a, const void *b)
{
return *(int *)a - *(int *)b;
}
int main()
{
int num[MAX], i = 0, length = 0;
FILE *fp;
errno = 0;
if((fp = fopen("text1", "r")) == NULL) {
fprintf(stderr, "Error: Cannot open text1. Reason: %s\n", strerror(errno));
exit(1);
}
while(!feof(fp)) {
fscanf(fp, "%d", &num[length]);
length++;
}
length--;
fclose(fp);
qsort(num, length, sizeof(int), int_cmp);
if((fp = fopen("text1_qsort", "wb")) == NULL) {
fprintf(stderr, "Error: Cannot open text1_qsort. Reason: %s\n", strerror(errno));
exit(1);
}
while(i < length)
fprintf(fp, "%d\n", num[i++]);
fclose(fp);
return 0;
}
注意:
a)qsort函数
num是指向数组的指针,length是数组长度,sizeof(int)是数组元素大小,int_cmp是指向函数的指针
函数说明:void qsort(void *base, size_t n, size_t size, int (*cmp)(const void *, const void *))
b)qsort函数中使用的int_cmp函数
int int_cmp(const void *a, const void *b)
{
}