Skip to content

Instantly share code, notes, and snippets.

@NalaGinrut
Last active December 14, 2015 21:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NalaGinrut/5151115 to your computer and use it in GitHub Desktop.
Save NalaGinrut/5151115 to your computer and use it in GitHub Desktop.
A Guile version 'cat' for Guile-100 project
#! /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))
@wingo
Copy link

wingo commented Mar 13, 2013

Use "when" instead of "and" when you don't need a result.

@wingo
Copy link

wingo commented Mar 13, 2013

_iolbf is line buffering; you want _ionbf

@wingo
Copy link

wingo commented Mar 13, 2013

use print-exception to display errors

@wingo
Copy link

wingo commented Mar 13, 2013

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