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 void
12 usage(void)
13 {
14 fprint(2, "usage: seq [-fformat] [-w] [first [incr]] last\n");
15 exits("usage");
16 }
18 void
19 buildfmt(void)
20 {
21 int i;
22 char *dp;
23 int w, p, maxw, maxp;
24 static char fmt[16];
25 char buf[32];
27 format = "%g\n";
28 if(!constant)
29 return;
30 maxw = 0;
31 maxp = 0;
32 for(i=0; i<=nsteps; i++){
33 sprint(buf, "%g", min+i*incr);
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 void
51 main(int argc, char *argv[]){
52 int i, j, n;
53 char buf[256], ffmt[4096];
55 ARGBEGIN{
56 case 'w':
57 constant++;
58 break;
59 case 'f':
60 format = ARGF();
61 if(format[strlen(format)-1] != '\n'){
62 sprint(ffmt, "%s\n", format);
63 format = ffmt;
64 }
65 break;
66 default:
67 goto out;
68 }ARGEND
69 out:
70 if(argc<1 || argc>3)
71 usage();
72 max = atof(argv[argc-1]);
73 if(argc > 1)
74 min = atof(argv[0]);
75 if(argc > 2)
76 incr = atof(argv[1]);
77 if(incr == 0){
78 fprint(2, "seq: zero increment\n");
79 exits("zero increment");
80 }
81 nsteps = (max-min)/incr+.5;
82 if(!format)
83 buildfmt();
84 for(i=0; i<=nsteps; i++){
85 n = sprint(buf, format, min+i*incr);
86 if(constant)
87 for(j=0; buf[j]==' '; j++)
88 buf[j] ='0';
89 write(1, buf, n);
90 }
91 exits(0);
92 }