c实现功能(9)对文本的内容进行排序

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void swap(int *p1, int *p2){
    int temp = *p1;
    *p1 = *p2;
    *p2 = temp;
}

//实现对数组内容的排序
void sort(int *p, int len){
    for(int i = 0; i < len; i++){
        for(int j = 0; j < len - i - 1; j++){
            if(p[j + 1] < p [j]){
                swap(&p[j], &p[j + 1]);
            }
        }
    }
}

void printArray(int *p,int len){
    for(int i = 0; i < len; i++){
        printf("%d\n",p[i]);
    }

}
int main1(){
    //在栈中实现对文本文件的内容进行排序
    int array[10] = {0};
    //利用字符缓冲区保存每次读取的文件内容
    char buf[100];
    int index = 0;

    //先打开需要排序的文件
    FILE *p = fopen("D:\\test\\a.txt","r");
    if(p == NULL){
        //文件不存在
        printf("File does not exist!");
    }else{
        //读取文件的内容
        while(!feof(p)){
            //每读取一行对buf的内容进行清除
            memset(buf, 0, sizeof (buf));
            fgets(buf, sizeof (buf), p);
            //将读取的字符串转换成int
            array[index] = atoi(buf);
            index++;
        }

        fclose(p);
    }



    //对数据进行排序
    sort(array,index);
    //打开需要写入的文件
    p = fopen("D:\\test\\b.txt", "w");
    for(int i = 0; i < index; i++){
        //每读取一行对buf的内容进行清除
        memset(buf, 0, sizeof (buf));
        //先将数组中的内容转换成字符串
        sprintf(buf, "%d\n", array[i]);
        //将数据保存到写入的数据中
        fputs(buf, p);
    }

    fclose(p);
    return 0;
}

int main(){
    //在堆中实现对文本文件的内容进行排序
    //利用字符缓冲区保存每次读取的文件内容
    char buf[100];
    int index = 0;

    //首先需要确定给数组分配多大的内存空间
    //打开文件,确定有多少行
    FILE *p = fopen("D:\\test\\a.txt","r");
    if(p == NULL){
        //文件不存在
        printf("File does not exist!");
    }else{
        //读取文件的内容
        while(!feof(p)){
            //每读取一行对buf的内容进行清除
            memset(buf, 0, sizeof (buf));
            fgets(buf, sizeof (buf), p);
            index++;
        }
    }

    //在堆中建立一个动态数组
    int *array = calloc(sizeof (int), index);
    index = 0;
    //再次打开文件
    p = fopen("D:\\test\\a.txt","r");
    //读取文件的内容
    while(!feof(p)){
        //每读取一行对buf的内容进行清除
        memset(buf, 0, sizeof (buf));
        fgets(buf, sizeof (buf), p);
        //将读取的字符串转换成int
        array[index] = atoi(buf);
        index++;
    }

    fclose(p);

    //对数据进行排序
    sort(array,index);
    //打开需要写入的文件
    p = fopen("D:\\test\\b.txt", "w");
    for(int i = 0; i < index; i++){
        //每读取一行对buf的内容进行清除
        memset(buf, 0, sizeof (buf));
        //先将数组中的内容转换成字符串
        sprintf(buf, "%d\n", array[i]);
        //将数据保存到写入的数据中
        fputs(buf, p);
    }

    fclose(p);
    free(array);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/hc1151310108/article/details/82939688