-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcsort.c
96 lines (75 loc) · 1.48 KB
/
csort.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define LINES 128
#define LINE_MAX 1024
struct csort_opt {
int k;
int r:1;
} _opt;
static char const * col(char const * a, int n)
{
if (n <= 1) {
return a;
}
int i = 0;
while (a[i] && isspace(a[i])) ++i;
++n;
while (a[i] && --n > 1) {
while (a[i] && !isspace(a[i])) ++i;
while (a[i] && isspace(a[i])) ++i;
}
return &a[i];
}
static
int compar(const void * _a, const void * _b)
{
char const * a = (char const*)_a;
char const * b = (char const*)_b;
char const * c0 = col(a, _opt.k);
char const * c1 = col(b, _opt.k);
if (_opt.r)
return strcmp(c1, c0);
return strcmp(c0, c1);
}
static void
usage(FILE * out, char const * binary)
{
fprintf(out,
"usage: %s [options]\n"
" -h this help message\n"
" -k N sort on column N\n"
" -r reverse sort\n"
, binary
);
}
int main(int argc, char * argv[])
{
int c;
while (c = getopt(argc, argv, "hk:r"), c != -1) {
switch (c) {
case 'h':
usage(stdout, basename(argv[0]));
exit(0);
case 'k':
_opt.k = atoi(optarg);
break;
case 'r':
_opt.r = 1;
break;
default:
usage(stderr, basename(argv[0]));
exit(-1);
}
}
char lines[LINES][LINE_MAX];
int line_count = 0;
while (line_count < LINES, fgets(lines[line_count++], LINE_MAX, stdin));
qsort(lines, line_count, LINE_MAX, compar);
for (int i = 0; i < line_count; ++i) {
printf("%s", lines[i]);
}
return 0;
}