#include #include 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); }