home *** CD-ROM | disk | FTP | other *** search
/ The C Users' Group Library 1994 August / wc-cdrom-cusersgrouplibrary-1994-08.iso / vol_200 / 221_01 / printf.c < prev    next >
Text File  |  1979-12-31  |  2KB  |  68 lines

  1. #define stdout 1
  2. #define ERR -99
  3. #define ERRCODE 99
  4. #define EOF -1
  5. #define NULL 0
  6. #define stderr 2
  7. extern int exit(), ccmult(), ccdiv();
  8. extern int putc(), fputs();
  9. /*
  10. ** printf(controlstring, arg, arg, ...) -- formatted print
  11. **        operates as described by Kernighan & Ritchie
  12. **        only d, x, c, s, and u specs are supported.
  13. */
  14. printf(argc) int argc; {
  15.   int  width, prec, preclen, len, *nxtarg;
  16.   char *ctl, *cx, c, right, str[7], *sptr, pad;
  17.   int i;
  18. #asm       /* fetch arg count from D reg first */
  19.  STD ,S
  20. #endasm
  21.   nxtarg = &argc + (i - 1 << 1);
  22.   ctl = *nxtarg;
  23.   while(c=*ctl++) {
  24.     if(c!='%') {cout(c, stdout); continue;}
  25.     if(*ctl=='%') {cout(*ctl++, stdout); continue;}
  26.     cx=ctl;
  27.     if(*cx=='-') {right=0; ++cx;} else right=1;
  28.     if(*cx=='0') {pad='0'; ++cx;} else pad=' ';
  29.     if((i=utoi(cx, &width)) >= 0) cx=cx+i; else continue;
  30.     if(*cx=='.') {
  31.       if((preclen=utoi(++cx, &prec)) >= 0) cx=cx+preclen;
  32.       else continue;
  33.       }
  34.     else preclen=0;
  35.     sptr=str; c=*cx++; i=*(--nxtarg);
  36.     if(c=='d') itod(i, str, 7);
  37.     else if(c=='x') itox(i, str, 7);
  38.     else if(c=='c') {str[0]=i; str[1]=NULL;}
  39.     else if(c=='s') sptr=i;
  40.     else if(c=='u') itou(i, str, 7);
  41.     else continue;
  42.     ctl=cx; /* accept conversion spec */
  43.     if(c!='s') while(*sptr==' ') ++sptr;
  44.     len=-1; while(sptr[++len]); /* get length */
  45.     if((c=='s')&&(len>prec)&&(preclen>0)) len=prec;
  46.     if(right) while(((width--)-len)>0) cout(pad, stdout);
  47.     while(len) {cout(*sptr++, stdout); --len; --width;}
  48.     while(((width--)-len)>0) cout(pad, stdout);
  49.     }
  50.   }
  51. cout(c, fd) char c; int fd; {
  52.   if(putc(c, fd)==EOF) xout();
  53.   }
  54.  
  55. sout(string, fd) char *string; int fd; {
  56.   if(fputs(string, fd)==EOF) xout();
  57.   }
  58.  
  59. lout(line, fd) char *line; int fd; {
  60.   sout(line, fd);
  61.   cout('\n', fd);
  62.   }
  63.  
  64. xout() {
  65.   fputs("output error\n", stderr);
  66.   exit(ERRCODE);
  67.   }
  68.