1 /* -*- mode: c; c-file-style: "k&r" -*-
3 natsort.c -- Example strnatcmp application.
5 Copyright (C) 2000 by Martin Pool <mbp@humbug.org.au>
7 This software is provided 'as-is', without any express or implied
8 warranty. In no event will the authors be held liable for any damages
9 arising from the use of this software.
11 Permission is granted to anyone to use this software for any purpose,
12 including commercial applications, and to alter it and redistribute it
13 freely, subject to the following restrictions:
15 1. The origin of this software must not be misrepresented; you must not
16 claim that you wrote the original software. If you use this software
17 in a product, an acknowledgment in the product documentation would be
18 appreciated but is not required.
19 2. Altered source versions must be plainly marked as such, and must not be
20 misrepresented as being the original software.
21 3. This notice may not be removed or altered from any source distribution.
24 /* Partial change history:
26 * 2003-03-18: Add --reverse option, from Alessandro Pisani.
36 #include "strnatcmp.h"
39 # define UNUSED __attribute__((__unused__))
42 static int fold_case
= 0, verbose
= 0, reverse
= 0;
44 static void trace_result(char const *a
, char const *b
, int ret
)
55 fprintf(stderr
, "\tstrncatcmp: \"%s\" %s \"%s\"\n",
61 static int compare_strings(const void *a
, const void *b
)
63 char const *pa
= *(char const **)a
, *pb
= *(char const **)b
;
67 ret
= strnatcasecmp(pa
, pb
);
69 ret
= strnatcmp(pa
, pb
);
75 trace_result(pa
, pb
, ret
);
81 static void usage(void)
83 fprintf(stderr
, "Usage: natsort [OPTIONS]\n"
84 "Performs a natural sort on standard input, and writes to \n"
87 " --help, -h show help text\n"
88 " --verbose, -v show comparisons\n"
89 " --fold-case, -f ignore case differences for letters\n"
90 " --reverse, -r reverse the result of comparisons\n");
94 int main(int argc
, char **argv
)
103 static struct option long_options
[] = {
104 { "verbose", 0, NULL
, 'v'},
105 { "reverse", 0, NULL
, 'r'},
106 { "fold-case", 0, NULL
, 'f'},
107 { "help", 0, 0, 'h' },
111 /* process arguments */
112 while ((c
= getopt_long(argc
, argv
, "frvh", long_options
, &opt_ind
)) != -1) {
133 /* read lines into an array */
137 if ((linelen
= getline(&line
, &bufsize
, stdin
)) <= 0)
139 if (line
[linelen
-1] == '\n')
142 list
= (char **) realloc(list
, nlines
* sizeof list
[0]);
144 perror("allocate list");
147 list
[nlines
-1] = line
;
157 qsort(list
, nlines
, sizeof list
[0], compare_strings
);
160 for (i
= 0; i
< nlines
; i
++) {
163 if (ferror(stdout
)) {