fileio.scm 2.9 KB

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