seq.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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. char *dp;
  19. int w, p, maxw, maxp;
  20. static char fmt[16];
  21. char buf[32];
  22. double val;
  23. format = "%g\n";
  24. if(!constant)
  25. return;
  26. maxw = 0;
  27. maxp = 0;
  28. for(val = min; val <= max; val += incr){
  29. sprint(buf, "%g", val);
  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 j, n;
  48. char buf[256], ffmt[4096];
  49. double val;
  50. ARGBEGIN{
  51. case 'w':
  52. constant++;
  53. break;
  54. case 'f':
  55. format = EARGF(usage());
  56. if(format[strlen(format)-1] != '\n'){
  57. sprint(ffmt, "%s\n", format);
  58. format = ffmt;
  59. }
  60. break;
  61. default:
  62. goto out;
  63. }ARGEND
  64. out:
  65. if(argc<1 || argc>3)
  66. usage();
  67. max = atof(argv[argc-1]);
  68. if(argc > 1)
  69. min = atof(argv[0]);
  70. if(argc > 2)
  71. incr = atof(argv[1]);
  72. if(incr == 0){
  73. fprint(2, "seq: zero increment\n");
  74. exits("zero increment");
  75. }
  76. if(!format)
  77. buildfmt();
  78. if(incr > 0){
  79. for(val = min; val <= max; val += incr){
  80. n = sprint(buf, format, val);
  81. if(constant)
  82. for(j=0; buf[j]==' '; j++)
  83. buf[j] ='0';
  84. write(1, buf, n);
  85. }
  86. }else{
  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. }
  95. exits(0);
  96. }