sbase/uniq.c

106 lines
1.6 KiB
C
Raw Normal View History

2012-05-21 19:24:28 -04:00
/* See LICENSE file for copyright and license details. */
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
2013-03-05 15:35:55 -05:00
2012-05-21 19:24:28 -04:00
#include "text.h"
#include "util.h"
static void uniq_line(char *);
static void uniq(FILE *, const char *);
static void uniq_finish(void);
static const char *countfmt = "";
static bool dflag = false;
static bool uflag = false;
static char *prev_line = NULL;
static long prev_line_count = 0;
2013-06-14 14:20:47 -04:00
static void
usage(void)
{
eprintf("usage: %s [-cdiu] [input]]\n", argv0);
2013-06-14 14:20:47 -04:00
}
2012-05-21 19:24:28 -04:00
int
main(int argc, char *argv[])
{
FILE *fp;
2013-06-14 14:20:47 -04:00
ARGBEGIN {
case 'i':
eprintf("not implemented\n");
2013-06-14 14:20:47 -04:00
case 'c':
countfmt = "%7ld ";
break;
case 'd':
dflag = true;
break;
case 'u':
uflag = true;
break;
default:
usage();
} ARGEND;
2012-05-21 19:24:28 -04:00
2013-06-14 14:20:47 -04:00
if(argc == 0) {
2012-05-21 19:24:28 -04:00
uniq(stdin, "<stdin>");
2013-06-14 14:20:47 -04:00
} else if(argc == 1) {
if(!(fp = fopen(argv[0], "r")))
eprintf("fopen %s:", argv[0]);
uniq(fp, argv[0]);
2012-05-21 19:24:28 -04:00
fclose(fp);
} else
2013-06-14 14:20:47 -04:00
usage();
2012-05-21 19:24:28 -04:00
uniq_finish();
2013-06-14 14:20:47 -04:00
return 0;
2012-05-21 19:24:28 -04:00
}
void
uniq_line(char *l)
{
bool lines_equal = ((l == NULL) || (prev_line == NULL))
? l == prev_line
: !strcmp(l, prev_line);
if(lines_equal) {
++prev_line_count;
return;
}
if(prev_line != NULL) {
if((prev_line_count == 1 && !dflag) ||
(prev_line_count != 1 && !uflag)) {
printf(countfmt, prev_line_count);
fputs(prev_line, stdout);
}
free(prev_line);
prev_line = NULL;
}
if(l && !(prev_line = strdup(l)))
eprintf("strdup:");
prev_line_count = 1;
}
void
uniq(FILE *fp, const char *str)
{
char *buf = NULL;
size_t size = 0;
while(afgets(&buf, &size, fp))
uniq_line(buf);
}
void
uniq_finish()
{
uniq_line(NULL);
}
2013-06-14 14:20:47 -04:00