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. 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 = ARGF();
  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. for(val = min; val <= max; val += incr){
  79. n = sprint(buf, format, val);
  80. if(constant)
  81. for(j=0; buf[j]==' '; j++)
  82. buf[j] ='0';
  83. write(1, buf, n);
  84. }
  85. exits(0);
  86. }