seq.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. /*
  2. * This file is part of the UCB release of Plan 9. It is subject to the license
  3. * terms in the LICENSE file found in the top-level directory of this
  4. * distribution and at http://akaros.cs.berkeley.edu/files/Plan9License. No
  5. * part of the UCB release of Plan 9, including this file, may be copied,
  6. * modified, propagated, or distributed except according to the terms contained
  7. * in the LICENSE file.
  8. */
  9. #include <u.h>
  10. #include <libc.h>
  11. double min = 1.0;
  12. double max = 0.0;
  13. double incr = 1.0;
  14. int constant = 0;
  15. int nsteps;
  16. char *format;
  17. void
  18. usage(void)
  19. {
  20. fprint(2, "usage: seq [-fformat] [-w] [first [incr]] last\n");
  21. exits("usage");
  22. }
  23. void
  24. buildfmt(void)
  25. {
  26. char *dp;
  27. int w, p, maxw, maxp;
  28. static char fmt[16];
  29. char buf[32];
  30. double val;
  31. format = "%g\n";
  32. if(!constant)
  33. return;
  34. maxw = 0;
  35. maxp = 0;
  36. for(val = min; val <= max; val += incr){
  37. sprint(buf, "%g", val);
  38. if(strchr(buf, 'e')!=0)
  39. return;
  40. dp = strchr(buf,'.');
  41. w = dp==0? strlen(buf): dp-buf;
  42. p = dp==0? 0: strlen(strchr(buf,'.')+1);
  43. if(w>maxw)
  44. maxw = w;
  45. if(p>maxp)
  46. maxp = p;
  47. }
  48. if(maxp > 0)
  49. maxw += maxp+1;
  50. sprint(fmt,"%%%d.%df\n", maxw, maxp);
  51. format = fmt;
  52. }
  53. void
  54. main(int argc, char *argv[]){
  55. int j, n;
  56. char buf[256], ffmt[4096];
  57. double val;
  58. ARGBEGIN{
  59. case 'w':
  60. constant++;
  61. break;
  62. case 'f':
  63. format = EARGF(usage());
  64. if(format[strlen(format)-1] != '\n'){
  65. sprint(ffmt, "%s\n", format);
  66. format = ffmt;
  67. }
  68. break;
  69. default:
  70. goto out;
  71. }ARGEND
  72. out:
  73. if(argc<1 || argc>3)
  74. usage();
  75. max = atof(argv[argc-1]);
  76. if(argc > 1)
  77. min = atof(argv[0]);
  78. if(argc > 2)
  79. incr = atof(argv[1]);
  80. if(incr == 0){
  81. fprint(2, "seq: zero increment\n");
  82. exits("zero increment");
  83. }
  84. if(!format)
  85. buildfmt();
  86. if(incr > 0){
  87. for(val = min; val <= max; val += incr){
  88. n = sprint(buf, format, val);
  89. if(constant)
  90. for(j=0; buf[j]==' '; j++)
  91. buf[j] ='0';
  92. write(1, buf, n);
  93. }
  94. }else{
  95. for(val = min; val >= max; val += incr){
  96. n = sprint(buf, format, val);
  97. if(constant)
  98. for(j=0; buf[j]==' '; j++)
  99. buf[j] ='0';
  100. write(1, buf, n);
  101. }
  102. }
  103. exits(0);
  104. }