ThinkGeek - Cool Stuff for Geeks and Technophiles

Tuesday, August 12, 2008

PIR file i/o

File I/O in PIR is very simple and straightforward, just as in a high-level language. Here's a short code snippet to read from an existing file and display its contents.



.sub main
.local string readfile
.local string data
.local pmc fd

readfile = 'read.txt'
print 'Opening: '
say readfile

fd = open readfile, '<'
data = readline fd
close fd
say data
say "File closed.\n"

.end



And here's one to read input from stdin, line by line. A blank line marks the end of input. As the lines are received, they are written to an output file. The final blank line is not written.



.sub main
.local string writefile
.local string data
.local pmc fd

writefile = 'write.txt'
fd = open writefile, '>'
say "Enter text to write. Blank line to end."
loop:
data = read 80
if data == "\n" goto lastline
print fd, data
goto loop
lastline:
print "Writing to "
say writefile
close fd
say "File closed."

.end



I'm a little puzzled about the read command. The Parrot IO API shows the following forms to be valid:

read(out STR, in INT): Read up to N bytes from standard input stream
read(out STR, invar PMC, in INT): Read up to N bytes from IO PMC stream.
readline(out STR, invar PMC): Read a line up to EOL from filehandle $2. This switches the filehandle to linebuffer-mode.

It seems to me that there ought to be a generic read(out STR) that reads until an EOF or a \n. Maybe there is a value (zero? minus one?) that causes read to behave this way. I'll have to do some more digging until I understand it better.

Labels: ,

0 Comments:

Post a Comment

Links to this post:

Create a Link

<< Home