1
0
mirror of git://git.suckless.org/sbase synced 2024-12-27 01:12:19 +00:00
sbase/sort.c

79 lines
1.4 KiB
C
Raw Normal View History

2011-06-02 12:03:34 +00:00
/* See LICENSE file for copyright and license details. */
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "text.h"
#include "util.h"
static int linecmp(const char **, const char **);
static bool rflag = false;
2011-06-02 12:09:30 +00:00
static bool uflag = false;
2013-12-12 13:08:49 +00:00
static bool nflag = false;
static struct linebuf linebuf = EMPTY_LINEBUF;
2013-06-14 18:20:47 +00:00
static void
usage(void)
{
2013-12-12 13:08:49 +00:00
eprintf("usage: %s [-nru] [file...]\n", argv0);
2013-06-14 18:20:47 +00:00
}
2011-06-02 12:03:34 +00:00
int
main(int argc, char *argv[])
{
long i;
FILE *fp;
2013-06-14 18:20:47 +00:00
ARGBEGIN {
2013-12-12 13:08:49 +00:00
case 'n':
nflag = true;
break;
2013-06-14 18:20:47 +00:00
case 'r':
rflag = true;
break;
case 'u':
uflag = true;
break;
default:
usage();
} ARGEND;
if(argc == 0) {
getlines(stdin, &linebuf);
2013-06-14 18:20:47 +00:00
} else for(; argc > 0; argc--, argv++) {
if(!(fp = fopen(argv[0], "r"))) {
weprintf("fopen %s:", argv[0]);
continue;
}
getlines(fp, &linebuf);
2011-06-02 12:03:34 +00:00
fclose(fp);
}
2013-06-14 18:20:47 +00:00
qsort(linebuf.lines, linebuf.nlines, sizeof *linebuf.lines,
(int (*)(const void *, const void *))linecmp);
2011-06-02 12:03:34 +00:00
2013-06-14 18:20:47 +00:00
for(i = 0; i < linebuf.nlines; i++) {
if(!uflag || i == 0 || strcmp(linebuf.lines[i],
linebuf.lines[i-1]) != 0) {
fputs(linebuf.lines[i], stdout);
2013-06-14 18:20:47 +00:00
}
}
return EXIT_SUCCESS;
2011-06-02 12:03:34 +00:00
}
int
linecmp(const char **a, const char **b)
{
2013-12-12 13:08:49 +00:00
if (nflag) {
if (rflag)
return strtoul(*b, 0, 10) - strtoul(*a, 0, 10);
else
return strtoul(*a, 0, 10) - strtoul(*b, 0, 10);
}
2011-06-02 12:03:34 +00:00
return strcmp(*a, *b) * (rflag ? -1 : +1);
}
2013-06-14 18:20:47 +00:00