examples-read-files.fth 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. \ Print lines from a text file.
  2. \ This prints lines from a file, but does not put them on
  3. \ the stack.
  4. 256 Constant max-bytes-line
  5. \ Create a buffer of appropriate size for lines. Add 2 bytes
  6. \ to the buffer size for CR LF bytes.
  7. Create line-buffer max-bytes-line 2 + allot
  8. s" input" r/o open-file throw Value puzzle-input-handle
  9. : print-line ( line-buffer -- )
  10. dup max-bytes-line puzzle-input-handle read-line throw
  11. if
  12. line-buffer swap
  13. then ;
  14. \ given a line-buffer, print-line will print one line per call
  15. line-buffer
  16. print-line
  17. print-line
  18. print-line
  19. \ Finally close the file.
  20. puzzle-input-handle close-file
  21. \ ================
  22. \ Interpret a file
  23. \ ================
  24. \ This can be useful, if the file contains only words which
  25. \ are valid Forth words and the input file is
  26. \ trusted. However, this discards any whitespace. If
  27. \ whitespace of the input file is significant, this method
  28. \ will fail.
  29. s" my-trusted-file" included
  30. .s
  31. \ ======================
  32. \ Read numbers from file
  33. \ ======================
  34. 256 Constant max-bytes-line
  35. Create line-buffer max-bytes-line 2 + allot
  36. s" input" r/o open-file throw Value puzzle-input-handle
  37. : add-nums-from-file ( c-addr length -- ??? )
  38. begin
  39. \ Read the next line from the puzzle input.
  40. line-buffer max-bytes-line puzzle-input-handle read-line throw
  41. \ stack: length eof-flag
  42. swap
  43. \ stack: eof-flag length
  44. \ Check if more than 0 characters were read as a number.
  45. dup 0 >
  46. \ stack: eof-flag length more-than-0-chars-flag
  47. rot
  48. \ stack: length more-than-0-chars-flag eof-flag
  49. \ Check that both true.
  50. and
  51. \ stack: length flag
  52. while
  53. \ stack: length
  54. \ Put a float at the bottom for >number which requires a
  55. \ double to be at specific position.
  56. 0.
  57. \ stack: length 0. 0
  58. rot
  59. \ stack: 0. 0 length
  60. line-buffer swap
  61. \ stack: 0. 0 length c-addr
  62. >number
  63. 2swap
  64. \ convert double to one integer number (?)
  65. d>s
  66. \ Use the numbers here. For now only dropping them.
  67. . drop drop
  68. repeat ;
  69. puzzle-input-handle close-file