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 **);
|
2011-06-21 04:05:37 +00:00
|
|
|
static void getlines(FILE *);
|
2011-06-02 12:03:34 +00:00
|
|
|
|
|
|
|
static bool rflag = false;
|
2011-06-02 12:09:30 +00:00
|
|
|
static bool uflag = false;
|
2011-06-02 12:03:34 +00:00
|
|
|
static char **lines = NULL;
|
|
|
|
static long nlines = 0;
|
|
|
|
|
|
|
|
int
|
|
|
|
main(int argc, char *argv[])
|
|
|
|
{
|
|
|
|
char c;
|
|
|
|
long i;
|
|
|
|
FILE *fp;
|
|
|
|
|
2011-06-02 12:09:30 +00:00
|
|
|
while((c = getopt(argc, argv, "ru")) != -1)
|
2011-06-02 12:03:34 +00:00
|
|
|
switch(c) {
|
|
|
|
case 'r':
|
|
|
|
rflag = true;
|
|
|
|
break;
|
2011-06-02 12:09:30 +00:00
|
|
|
case 'u':
|
|
|
|
uflag = true;
|
|
|
|
break;
|
2011-06-02 12:03:34 +00:00
|
|
|
default:
|
|
|
|
exit(EXIT_FAILURE);
|
|
|
|
}
|
|
|
|
if(optind == argc)
|
2011-06-21 04:05:37 +00:00
|
|
|
getlines(stdin);
|
2011-06-02 12:03:34 +00:00
|
|
|
else for(; optind < argc; optind++) {
|
|
|
|
if(!(fp = fopen(argv[optind], "r")))
|
|
|
|
eprintf("fopen %s:", argv[optind]);
|
2011-06-21 04:05:37 +00:00
|
|
|
getlines(fp);
|
2011-06-02 12:03:34 +00:00
|
|
|
fclose(fp);
|
|
|
|
}
|
|
|
|
qsort(lines, nlines, sizeof *lines, (int (*)(const void *, const void *))linecmp);
|
|
|
|
|
2011-06-02 12:09:30 +00:00
|
|
|
for(i = 0; i < nlines; i++)
|
2011-06-04 11:27:44 +00:00
|
|
|
if(!uflag || i == 0 || strcmp(lines[i], lines[i-1]) != 0)
|
2011-06-02 12:09:30 +00:00
|
|
|
fputs(lines[i], stdout);
|
2011-06-02 12:03:34 +00:00
|
|
|
return EXIT_SUCCESS;
|
|
|
|
}
|
|
|
|
|
|
|
|
void
|
2011-06-21 04:05:37 +00:00
|
|
|
getlines(FILE *fp)
|
2011-06-02 12:03:34 +00:00
|
|
|
{
|
|
|
|
char *line = NULL;
|
|
|
|
size_t size = 0;
|
|
|
|
|
|
|
|
while(afgets(&line, &size, fp)) {
|
|
|
|
if(!(lines = realloc(lines, ++nlines * sizeof *lines)))
|
|
|
|
eprintf("realloc:");
|
|
|
|
if(!(lines[nlines-1] = malloc(strlen(line)+1)))
|
|
|
|
eprintf("malloc:");
|
|
|
|
strcpy(lines[nlines-1], line);
|
|
|
|
}
|
|
|
|
free(line);
|
|
|
|
}
|
|
|
|
|
|
|
|
int
|
|
|
|
linecmp(const char **a, const char **b)
|
|
|
|
{
|
|
|
|
return strcmp(*a, *b) * (rflag ? -1 : +1);
|
|
|
|
}
|