seq.c 1.4 KB

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