Shammer's Philosophy

My private adversaria

Lisp IO 総まとめ-20100205

Lisp IO 基本総まとめ - Shammerismの内容に一部追加。

File 読み込み

(with-open-file (input-stream "$READ_FILE_NAME" :direction :input)
  (loop
    (let ((line (read-line input-stream nil 'eof)))
      (if (eql line 'eof) (return))
	(format t "~A~%" line)))))
(with-open-file (stream path :direction :input)
  (do ((line ;Value Name
        (read-line stream nil 'eof) ;Initial Value
        (read-line stream nil 'eof))) ;Step
      ((eql line 'eof)) ; Finish Judgement
    (format t "~A~%" line)))

File 書き出し

(with-open-file (output-stream "$OUTPUT_FILE_NAME" :direction :output)
  (format output-stream "Hello!"))

File 書き足し

(with-open-file (stream path :direction :output :if-exists :append :if-does-not-exist :error)
  (format stream "~A~%" "Hello, World!")
  (format stream "~A~%" "END OF FILE"))

Passive Socket

(defun open-echo-server ()
  (with-open-socket (server :type :stream
			    :connect :passive
			    :local-host "localhost"
			    :local-port 8080
			    :reuse-address t)
		    (let ((client (accept-connection server)))
		      (format t "> Server received a message: ~%")
		      (do ((line (read-line client nil nil)
				 (read-line client nil nil)))
			  ((or (string-equal line (string '#\Return))
			        (eql line nil)))
			(dolist (i (coerce line 'list))
			  (format t "~:c" i))
			(format t "~%"))
		      (format t "> Received Complete...~%")
		      (close client))))

Active Socket

(defun send-message (destination-host destination-port message)
  (with-open-socket (client :address-family :internet
			    :type :stream
			    :connect :active
			    :remote-host destination-host
			    :remote-port destination-port)
		    (format client message)
		    (format client "~%")
		    (force-output client)))