Last active
December 14, 2015 21:28
A Guile version 'cat' for Guile-100 project
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/env guile | |
!# | |
(use-modules (ice-9 getopt-long)) | |
(setlocale LC_ALL "") | |
(define cur-out (current-output-port)) | |
(define cur-in (current-input-port)) | |
(define option-spec | |
'((version (single-char #\v) (value #f)) | |
(help (single-char #\h) (value #f)) | |
(unbuffered (single-char #\u) (value #f)))) | |
;; NOTE: I don't think we need this line in Guile | |
;;(sigaction SIGINT (lambda (msg) (exit 130))) | |
(define (show-help) | |
(display | |
" | |
-u --unbuffered | |
Do no buffering. Write bytes from the input to the standard output without delay as each character is read. | |
-h --help | |
Print out command help. | |
-v --version | |
Print out the program name and version number.\n")) | |
(define (show-version) | |
(display "Cat on Guile v0.0.1\n")) | |
(define (cat-contents in no-buffered) | |
(when no-buffered (setvbuf in _IONBF) (setvbuf cur-out _IONBF)) | |
((@ (rnrs io ports) put-bytevector) cur-out ((@ (rnrs io ports) get-bytevector-all) in)) | |
(and no-buffered (flush-all-ports))) | |
(define (cat-all files no-buffered) | |
(define cat (lambda (p) (cat-contents p no-buffered))) | |
(for-each cat (map open-input-file files))) | |
(define (try-cat files no-buffered) | |
(catch 'system-error | |
(lambda () | |
(if (null? files) | |
(cat-contents cur-in no-buffered) | |
(cat-all files no-buffered))) | |
(lambda (k . e) | |
(print-exception (current-error-port) #f k e) | |
(exit 1)))) | |
(define (main args) | |
(let* ((options (getopt-long args option-spec)) | |
(need-help (option-ref options 'help #f)) | |
(need-version (option-ref options 'version #f)) | |
(no-buffered (option-ref options 'unbuffered #f)) | |
(files (option-ref options '() #f))) | |
(cond | |
(need-help (show-help)) | |
(need-version (show-version)) | |
(else (try-cat files no-buffered))))) | |
(main (command-line)) |
_iolbf is line buffering; you want _ionbf
use print-exception to display errors
surely cat should be binary and not textual
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use "when" instead of "and" when you don't need a result.