Blob
1 #include <u.h>2 #include <libc.h>4 double min = 1.0;5 double max = 0.0;6 double incr = 1.0;7 int constant = 0;8 int nsteps;9 char *format;11 void12 usage(void)13 {14 fprint(2, "usage: seq [-fformat] [-w] [first [incr]] last\n");15 exits("usage");16 }18 void19 buildfmt(void)20 {21 char *dp;22 int w, p, maxw, maxp;23 static char fmt[16];24 char buf[32];25 double val;27 format = "%g\n";28 if(!constant)29 return;30 maxw = 0;31 maxp = 0;32 for(val = min; val <= max; val += incr){33 sprint(buf, "%g", val);34 if(strchr(buf, 'e')!=0)35 return;36 dp = strchr(buf,'.');37 w = dp==0? strlen(buf): dp-buf;38 p = dp==0? 0: strlen(strchr(buf,'.')+1);39 if(w>maxw)40 maxw = w;41 if(p>maxp)42 maxp = p;43 }44 if(maxp > 0)45 maxw += maxp+1;46 sprint(fmt,"%%%d.%df\n", maxw, maxp);47 format = fmt;48 }50 void51 main(int argc, char *argv[]){52 int j, n;53 char buf[256], ffmt[4096];54 double val;56 ARGBEGIN{57 case 'w':58 constant++;59 break;60 case 'f':61 format = ARGF();62 if(format[strlen(format)-1] != '\n'){63 sprint(ffmt, "%s\n", format);64 format = ffmt;65 }66 break;67 default:68 goto out;69 }ARGEND70 out:71 if(argc<1 || argc>3)72 usage();73 max = atof(argv[argc-1]);74 if(argc > 1)75 min = atof(argv[0]);76 if(argc > 2)77 incr = atof(argv[1]);78 if(incr == 0){79 fprint(2, "seq: zero increment\n");80 exits("zero increment");81 }82 if(!format)83 buildfmt();84 if(incr > 0){85 for(val = min; val <= max; val += incr){86 n = sprint(buf, format, val);87 if(constant)88 for(j=0; buf[j]==' '; j++)89 buf[j] ='0';90 write(1, buf, n);91 }92 }else{93 for(val = min; val >= max; val += incr){94 n = sprint(buf, format, val);95 if(constant)96 for(j=0; buf[j]==' '; j++)97 buf[j] ='0';98 write(1, buf, n);99 }100 }101 exits(0);102 }