c - 文件编号升序排列

标签 c

如何读取包含两列的文件并按升序对第一列编号进行排序,并使用 C 打印它们及其相应的第二列值?

最佳答案

fopen打开一个文件。

fscanf从文件中读取并根据格式规范将读取的内容拆分为位(例如 "%d %s" 表示一个整数,后跟空格,后跟一串非空格字符)。

qsort是一个标准库函数,用于对数组进行排序。它通过将一项与另一项进行比较来对数组进行排序。您为其指定执行此比较的函数(您编写的)的名称。

如果您不熟悉这些函数,我鼓励您阅读它们的手册页。

下面的程序使用所有这些来:

  1. 打开文件 test.txt
  2. 将文件中的行读入数组 arr
  3. 使用 qsort 对数组进行排序,使用 rowcmp 函数(rowcmp 查看第一列中的数值来确定一个元素是否大于、等于或小于另一个元素)
  4. 打印出数组的元素。

代码...

#include <stdio.h>
#include <stdlib.h>
#define MAXLEN 100
#define MAXITEMS 100

// A row has two columns, the first is a number and
// the second is any string of up to MAXLEN chars
struct row {
    int col1;
    char col2[MAXLEN];
};

// Function to do comparison of rows
// Sorts numerically on the value in the first column
int rowcmp(struct row * r1, struct row * r2) {
    if (r1->col1 < r2->col1) return -1;
    if (r1->col1 == r2->col1) return 0; 
    return 1; 
}

int main(int argc, char ** argv) {

    struct row arr[MAXITEMS]; // up to MAXITEMS rows
    int rows = 0, i;
    FILE * stream = fopen("test.txt", "r");

    // Read in rows and put first and second columns into struct,
    // building up an array
    while (fscanf(stream, "%d %s", &(arr[rows].col1), arr[rows].col2) !=EOF) {
        rows++;
    }

    // Sort the array using the rowcmp function to compare items
    qsort(&arr[0], rows, sizeof(struct row), (__compar_fn_t)rowcmp);

    fclose(stream);

    // Print the sorted array
    for (i=0; i<rows; i++) {
        printf("%d\t%s\n", arr[i].col1, arr[i].col2);
    }
}

使用输入文件:

1 apple
3 cucumbers
21 dates
7 figs
4 grapes

输出为

1   apple
3   cucumbers
4   grapes
7   figs
21  dates

关于c - 文件编号升序排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26794889/

相关文章:

最长不重复子串算法代码复杂度

c - linux 将时间(针对不同的时区)转换为 UTC

c - 如何使用预处理器获取函数签名并声明另一个具有相同签名的函数?

c - C 判断文件中是否包含字符串

c - 如何打印彩色空格并在A之后关闭颜色代码?

c - 使用命令行参数声明结构

c - 如何使用ed25519加密/解密数据?

c - 为什么我的结构副本发生了变化?

c - 消息 "warning: implicit declaration of function"

c - 为什么要使用双重间接?或者为什么使用指向指针的指针?