file.scm 2.6 KB

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