如何读取包含两列的文件并按升序对第一列编号进行排序,并使用 C 打印它们及其相应的第二列值?
最佳答案
fopen
打开一个文件。
fscanf
从文件中读取并根据格式规范将读取的内容拆分为位(例如 "%d %s"
表示一个整数,后跟空格,后跟一串非空格字符)。
qsort
是一个标准库函数,用于对数组进行排序。它通过将一项与另一项进行比较来对数组进行排序。您为其指定执行此比较的函数(您编写的)的名称。
如果您不熟悉这些函数,我鼓励您阅读它们的手册页。
下面的程序使用所有这些来:
- 打开文件
test.txt
- 将文件中的行读入数组
arr
- 使用
qsort
对数组进行排序,使用 rowcmp 函数(rowcmp 查看第一列中的数值来确定一个元素是否大于、等于或小于另一个元素) - 打印出数组的元素。
代码...
#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/