/* shorten.c Strip trailing spaces and lines and DOS-isms in a text file. * DWF 2/21/92 * * Somewhat improved at the cost of uglifying the code 4/15/94 DWF. * -- Lines longer than 1000 characters are now handled correctly * -- Trailing tab characters are also stripped * * Bugs: * Vertical tabs and form feeds at the end of the file should be removed. */ #include #include #include #include #define blocksize 1000 /* Vertical tabs and form feeds are retained. Backspaces are retained because * they might be destructive on somebody's terminal. */ int spacey (char a) { return (a == ' ' || a == '\n' || a == '\r' || a == '\t'); } #define append {longbuflen += l; \ assert (longbuf = (char *) realloc (longbuf, longbuflen)); \ memcpy (longbuf+longbuflen-l, linrec, l);} /* Careful not to evaluate longbuf[-1] */ #define endspace (l ? spacey (longbuf[l-1]) : 0) main () { char linrec[blocksize], *longbuf=NULL; int bcount=0; size_t longbuflen=0, l; while (fgets (linrec, blocksize, stdin)) { assert (l = strlen (linrec)); if (linrec[l-1] != '\n') append else { if (!longbuflen) longbuf = linrec; else { l++; /* Get the \0 */ append l = longbuflen - 1; } while (endspace) longbuf[--l] = '\0'; if (!l) bcount++; else { for (; bcount; bcount--) printf ("\n"); printf ("%s\n", longbuf); } if (longbuflen) { longbuflen = 0; free (longbuf); } longbuf = NULL; } } if (longbuflen) { /* The last line wasn't terminated. */ linrec[0] = '\0'; l = 1; append l = longbuflen - 1; while (endspace) longbuf[--l] = '\0'; if (l) { for (; bcount; bcount--) printf ("\n"); printf ("%s", longbuf); } } return 0; }