reading from stdin on mac via buffer

Started by cormullion, February 26, 2007, 10:53:31 AM

Previous topic - Next topic

cormullion

I'm using this code to read from stdin on MacOS:


(set 'counter 0)
(while (read-buffer 0 'buff 256 "r")
  (print (inc 'counter) { } buff))


It works OK, but doesn't get the final line (which probably doesn't have a "r" to read). What's the best way to get the last bit?



(this is part of my ongoing battle getting Services to work with ThisService and those Mac applications that use "r" as line endings... :-))

Lutz

#1
Yoy shouldn't use 'r' (carriage return) to look for an end-of-line but "n". (line-feed). The following code does it all and will not require a line-feed after the last line:


(while (read-line)
        (println (current-line)))


or like this:


(while (set 'line (read-line))
        (println line))


This code will work not only on Mac OS X but on any UNIX and Win32.



See also here: http://newlisp.org/CodePatterns.html#scripts">http://newlisp.org/CodePatterns.html#scripts in the sub chapter: 'Scripts as pipes'



Lutz



ps: in your example it did get the second line. Although 'read-buffer' returned 'nil' the last characters are in 'buff'. See also http://newlisp.org/downloads/newlisp_manual.html#read-buffer">http://newlisp.org/downloads/newlisp_ma ... ead-buffer">http://newlisp.org/downloads/newlisp_manual.html#read-buffer for this.

cormullion

#2
Unfortunately "n" doesn't work, since the lines are separated by "r"...



(see http://www.alh.net/newlisp/phpbb/viewtopic.php?t=891">//http://www.alh.net/newlisp/phpbb/viewtopic.php?t=891)



But I'll see if buff stores the remaining characters...



thanks lutz