#include /* MS Dos / Windows doesn't include getopt as part of any standard libraries. Borland include an example getopt implementation in their Borland C version 2 for DOS package, which is included here to make wrap2.c compile on DOS-based platforms. */ /* START OF BORLAND CODE */ #include #include #include #include int optind = 1; /* index of which argument is next */ char *optarg; /* pointer to argument of current option */ int opterr = 1; /* allow error message */ static char *letP = NULL; /* remember next option char's location */ static char SW = 0; /* DOS switch character, either '-' or '/' */ int getopt(int argc, char *argv[], char *optionS) { unsigned char ch; char *optP; if (SW == 0) { /* get SW using dos call 0x37 */ _AX = 0x3700; geninterrupt(0x21); SW = _DL; } if (argc > optind) { if (letP == NULL) { if ((letP = argv[optind]) == NULL || *(letP++) != SW) goto gopEOF; if (*letP == SW) { optind++; goto gopEOF; } } if (0 == (ch = *(letP++))) { optind++; goto gopEOF; } if (':' == ch || (optP = strchr(optionS, ch)) == NULL) goto gopError; if (':' == *(++optP)) { optind++; if (0 == *letP) { if (argc <= optind) goto gopError; letP = argv[optind++]; } optarg = letP; letP = NULL; } else { if (0 == *letP) { optind++; letP = NULL; } optarg = NULL; } return ch; } gopEOF: optarg = letP = NULL; return EOF; gopError: optarg = NULL; errno = EINVAL; if (opterr) perror ("get command line option"); return ('?'); } /* END OF BORLAND CODE */ int WIDTH=80; int LIMIT=0; /* ** Note that the LIMIT is unimplemented ... probably I'm too stupid. ** The idea is: ** $ echo Hello | wrap -c 4 ** Hello ** $ echo Hello | wrap -c 4 -l ** Hell ** o ** $ ** Ie, making the -c limit actually mean something definite. */ void usage() { printf("Usage: wrap [-c CHARS] [-l LIMIT] [filename]\n"); exit(3); } FILE *scan_args(int argc, char *argv[]) { char c=NULL; FILE *infile; while (c>=0) { c=getopt(argc, argv, "lc:?"); switch (c) { case 'l': LIMIT=1; break; case 'c': WIDTH=atoi(optarg); break; case '?' : usage(); break; } } if (optind < argc) infile=fopen(argv[optind], "r"); else infile=stdin; /* cool! we can ungetc on stdin! I was sure it didn't work! Must check on Solaris... */ return infile; } void wrap(FILE *infile) { int n; char *buf=(char*)malloc(WIDTH+1); while (!feof(infile)) { fgets(buf, WIDTH, infile); n=strlen(buf); if ( (n>(WIDTH-2)) && (strchr(buf, ' ')) ) { n--; while (buf[n]!=' ') { ungetc(buf[n--], infile); } buf[n]='\n'; buf[n+1]='\0'; } if (!feof(infile)) printf("%s", buf); } free(buf); } main(int argc, char *argv[]) { int n; FILE *infile; infile=scan_args(argc, argv); wrap(infile); fclose(infile); }