PLEAC examples - 7. File Access

7.0. Introduction

Nothing is more central to data processing than the file.

This chapter deals with the mechanics of file access: opening a file, telling subroutines which files to work with, and so on.

7.0.1. Introduction

This example is about reading STDIN until EOF.

This is not useful when STDIN is assigned to the terminal, but can be used when STDIN is redirected to a file, as shown here!

First create an input file called 'stdinfile':
Roses are Red
Violets are blue
Rain on my head
Winter is due
then create the script 'stdinread':
#!/usr/bin/picolisp /usr/lib/picolisp/lib.l
(println "Type a few lines and end with ctrl+d")
(setq Var (in NIL (till NIL T)))
(println Var)
(println "Program is finished!")
(bye)
Then execute the next Linux commands:
chmod 777 stdinread
./stdinread <stdinfile

7.0.2. A few examples on opening, reading and writing

   # Example 1 - Read STDIN till EOF

   : (setq Var (in NIL (till NIL T)))
   This is a line
   a peaceful line
   it is not drunk
   it drinks no wine
   # Here I pressed ctrl+d which forces PicoLisp to end,
   # but it cannot detect an EOF this way ...

   # Example 2 - Write to a log file

   : (out "LogFile"
       (println "First line of log")
       (println "Second line of log"))
   -> "Second line of log"

   : (in "LogFile"
       (until (eof)
         (println (line T))))
   ""First line of log""
   ""Second line of log""
   -> ""Second line of log""

   # Example 3 - Append to that log file

   : (out "+LogFile"
       (println "Third line of log")
       (println "Last line of log"))
   -> "Last line of log"

   : (in "LogFile"
       (until (eof)
         (println (line T))))
   ""First line of log""
   ""Second line of log""
   ""Third line of log""
   ""Last line of log""
   -> ""Last line of log""

   # Open that log file for input using a handle
   #    Note: without flag T the file would be opened as Read/Write

   : (setq Fd (open "LogFile" T))
   -> 3

   : (in Fd
       (until (eof)
         (println (line T))))
   ""First line of log""
   ""Second line of log""
   ""Third line of log""
   ""Last line of log""
   -> ""Last line of log""

   : (close Fd)
   -> 3


https://picolisp.com/wiki/?pcepleacfiles

23jun18    ArievW