From 61c21ff1cf7a7381845065eb5c7a4d08624ad5dc Mon Sep 17 00:00:00 2001 From: tjr Date: Fri, 21 Jun 2002 07:08:34 +0000 Subject: Newline characters should not participate in line comparisons. Only apparent when -s is used or the last line of the file is missing a newline. Noticed by the textutils test suite. MFC after: 1 week --- usr.bin/uniq/uniq.c | 26 ++++++++++++++++++++++---- 1 file changed, 22 insertions(+), 4 deletions(-) (limited to 'usr.bin/uniq/uniq.c') diff --git a/usr.bin/uniq/uniq.c b/usr.bin/uniq/uniq.c index 701e58b..85733f0 100644 --- a/usr.bin/uniq/uniq.c +++ b/usr.bin/uniq/uniq.c @@ -63,6 +63,7 @@ int cflag, dflag, uflag; int numchars, numfields, repeats; FILE *file(const char *, const char *); +char *getline(char *, size_t, FILE *); void show(FILE *, char *); char *skip(char *); void obsolete(char *[]); @@ -137,10 +138,10 @@ main (argc, argv) if (prevline == NULL || thisline == NULL) errx(1, "malloc"); - if (fgets(prevline, MAXLINELEN, ifp) == NULL) + if (getline(prevline, MAXLINELEN, ifp) == NULL) exit(0); - while (fgets(thisline, MAXLINELEN, ifp)) { + while (getline(thisline, MAXLINELEN, ifp)) { /* If requested get the chosen fields + character offsets. */ if (numfields || numchars) { t1 = skip(thisline); @@ -169,6 +170,23 @@ main (argc, argv) exit(0); } +char * +getline(char *buf, size_t buflen, FILE *fp) +{ + size_t bufpos; + int ch; + + bufpos = 0; + while (bufpos + 2 != buflen && (ch = getc(fp)) != EOF && ch != '\n') + buf[bufpos++] = ch; + if (bufpos + 1 != buflen) + buf[bufpos] = '\0'; + while (ch != EOF && ch != '\n') + ch = getc(fp); + + return (bufpos != 0 || ch == '\n' ? buf : NULL); +} + /* * show -- * Output a line depending on the flags and number of repetitions @@ -181,9 +199,9 @@ show(ofp, str) { if (cflag && *str) - (void)fprintf(ofp, "%4d %s", repeats + 1, str); + (void)fprintf(ofp, "%4d %s\n", repeats + 1, str); if ((dflag && repeats) || (uflag && !repeats)) - (void)fprintf(ofp, "%s", str); + (void)fprintf(ofp, "%s\n", str); } char * -- cgit v1.1