Posted to tcl by lmcvoy at Fri Oct 19 17:17:55 GMT 2007view raw

  1. /*
  2. * stdio stuff (some above because we don't have {*} yet).
  3. */
  4. typedef string FILE;
  5. FILE stdin = "stdin";
  6. FILE stderr = "stderr";
  7. FILE stdout = "stdout";
  8. string stdio_lasterr;
  9.  
  10. FILE
  11. fopen(string path, string mode)
  12. {
  13. FILE f;
  14. string err;
  15. int v = 0;
  16.  
  17. /* new mode, v, means be verbose w/ errors */
  18. if (mode =~ /v/) {
  19. mode =~ s/v//;
  20. v = 1;
  21. }
  22. if (catch("set f [open {${path}} ${mode}]", &err)) {
  23. stdio_lasterr = err;
  24. if (v) fprintf(stderr, "fopen(%s, %s) = %s\n", path, mode, err);
  25. return (0);
  26. } else {
  27. return (f);
  28. }
  29. }
  30.  
  31. FILE
  32. popen(string cmd, string mode)
  33. {
  34. FILE f;
  35. string err;
  36. int v = 0;
  37.  
  38. if (mode =~ /v/) {
  39. mode =~ s/v//;
  40. v = 1;
  41. }
  42. if (catch("set f [open {|${cmd}} ${mode}]", &err)) {
  43. stdio_lasterr = err;
  44. if (v) fprintf(stderr, "popen(%s, %s) = %s\n", cmd, mode, err);
  45. return (0);
  46. } else {
  47. return (f);
  48. }
  49. }
  50.  
  51. int
  52. fclose(FILE f)
  53. {
  54. string err = "";
  55.  
  56. if (f eq "") return (0);
  57. if (catch("close ${f}", &err)) {
  58. stdio_lasterr = err;
  59. return (-1);
  60. } else {
  61. return (0);
  62. }
  63. }
  64.  
  65. int pclose(FILE f) { return (fclose(f)); }
  66.  
  67. int
  68. fgetline(FILE f, string &buf)
  69. {
  70. return (gets(f, &buf));
  71. }
  72.  
  73. string
  74. stdio_getLastError()
  75. {
  76. return (stdio_lasterr);
  77. }
  78.  
  79. /*
  80. * string functions
  81. */
  82. int
  83. streq(string a, string b)
  84. {
  85. return (string("compare", a, b));
  86. }
  87.  
  88. int
  89. strneq(string a, string b, int n)
  90. {
  91. return (string("compare", length: n, a, b));
  92. }
  93.  
  94. string
  95. strchr(string s, string c)
  96. {
  97. return (string("first", c, s));
  98. }
  99.  
  100. string
  101. strrchr(string s, string c)
  102. {
  103. return (string("last", c, s));
  104. }
  105.  
  106. int
  107. strlen(string s)
  108. {
  109. return (string("length", s));
  110. }
  111.  
  112. void
  113. chomp(string &s)
  114. {
  115. s = string("trimright", s, "\r\n");
  116. }
  117.  
  118. ===============================================
  119.  
  120. Simplistic cat.
  121.  
  122.  
  123. main(int ac, string av[])
  124. {
  125. string buf;
  126. FILE f;
  127. int i;
  128.  
  129. for (i = 1; i < ac; ++i) {
  130. unless (f = fopen(av[i], "rv")) continue;
  131. while (fgetline(f, &buf) >= 0) {
  132. printf("%s\n", buf);
  133. }
  134. fclose(f);
  135. }
  136. }
  137.