fileio.scm 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. (library (fileio)
  2. (export get-string-from-file
  3. get-lines-from-file
  4. get-lines-from-port
  5. get-lines-from-file-using-splitting
  6. put-lines-to-file
  7. put-string-to-file)
  8. (import
  9. (except (rnrs base)
  10. let-values
  11. map)
  12. (only (guile)
  13. lambda* λ
  14. ;; file io
  15. call-with-input-file
  16. call-with-output-file
  17. set-port-encoding!
  18. eof-object?
  19. ;; strings
  20. string-split
  21. string-join)
  22. (ice-9 textual-ports) ; for textual reading and writing procedures
  23. (ice-9 binary-ports) ; not sure if needed
  24. (ice-9 rdelim) ; for `eof-object?`
  25. )
  26. (define get-string-from-file
  27. (lambda* (file-path
  28. #:key
  29. (encoding "UTF-8"))
  30. (call-with-input-file file-path
  31. (λ (port)
  32. (set-port-encoding! port encoding)
  33. (get-string-all port)))))
  34. (define get-lines-from-file
  35. (lambda* (file-path
  36. #:key
  37. (encoding "UTF-8"))
  38. ;; another common encoding is: "ISO-8859-1"
  39. ;; see http://www.iana.org/assignments/character-sets for more
  40. (define (get-lines-from-port port)
  41. (let ([line (get-line port)])
  42. (cond [(eof-object? line) '()]
  43. [else
  44. (cons line
  45. (get-lines-from-port port))])))
  46. (call-with-input-file file-path
  47. (λ (port)
  48. (set-port-encoding! port encoding)
  49. (get-lines-from-port port)))))
  50. (define get-lines-from-file-using-splitting
  51. (lambda* (file-path
  52. #:key
  53. (encoding "UTF-8"))
  54. (string-split (get-string-from-file file-path #:encoding encoding)
  55. ;; You could use simple character here, but I am using
  56. ;; lambda to show that it can be used as well.
  57. (λ (char) (char=? char #\newline)))))
  58. (define put-lines-to-file
  59. (lambda* (file-path
  60. lines
  61. #:key
  62. (encoding "UTF-8")
  63. (mode 'replace))
  64. (call-with-output-file file-path
  65. (λ (port)
  66. (set-port-encoding! port encoding)
  67. (put-string port
  68. (cond
  69. [(eq? mode 'append)
  70. (string-append (get-string-from-file
  71. file-path
  72. #:encoding encoding)
  73. "\n"
  74. (string-join lines "\n"))]
  75. [(equal? mode 'replace) (string-join lines "\n")]
  76. [else (string-join lines "\n")]))))))
  77. (define put-string-to-file
  78. (lambda* (file-path
  79. string
  80. #:key
  81. (encoding "UTF-8")
  82. (mode 'replace))
  83. (call-with-output-file file-path
  84. (λ (port)
  85. (set-port-encoding! port encoding)
  86. (put-string port
  87. (cond
  88. [(eq? mode 'append)
  89. (string-append (get-string-from-file
  90. file-path
  91. #:encoding encoding)
  92. "\n"
  93. string)]
  94. [(equal? mode 'replace) string]
  95. [else string])))))))