C File Reading and Sorting Tutorial

Below is a sample program demonstrating how to read file data and sort the data.

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

// 用于比较两个整数的函数,用于排序
int compare(const void *a, const void *b) {
    return (*(int*)a - *(int*)b);
}

int main() {
    FILE *file;
    int data[100]; // 数组用于存储读取的数据
    int numData = 0; // 存储读取的数据数量

    // 打开文件
    file = fopen("data.txt", "r");
    if (file == NULL) {
        printf("无法打开文件\n");
        return 1;
    }

    // 读取文件数据
    while (fscanf(file, "%d", &data[numData]) != EOF) {
        numData++;
    }

    // 关闭文件
    fclose(file);

    // 对数据进行排序
    qsort(data, numData, sizeof(int), compare);

    // 打印排序后的数据
    printf("排序后的数据:\n");
    for (int i = 0; i < numData; i++) {
        printf("%d\n", data[i]);
    }

    return 0;
}

In this sample program, we first define a function called compare for comparing two integers, which is called during sorting. We then open a file named data.txt, read the data from the file and store it in an array. Next, we use the qsort function to sort the data in the array, and finally print the sorted data.

Please make sure to create a file named data.txt and input some integer data on each line before running the program. Once the program is run, it will read the data from the file and output the sorted results.

bannerAds