Is it there a better way to read a file in a list ?

For the Compleat Fan
Locked
Maurizio
Posts: 52
Joined: Mon Jul 28, 2003 3:06 pm
Location: Italy

Is it there a better way to read a file in a list ?

Post by Maurizio »

I'd like to read a file in a list, having each line as a separate string.
I've tried this, but it seems to me a little clumsy.
Is it there a better way ?
Regards
Maurizio

Code: Select all

(define (read-my-file)
  (set 'lst '())
  (set 'in-file (open "myfile.txt" "read"))
  (while (read-line in-file) 
    (set 'lst (append lst (list (current-line)))))
  (close in-file)
  lst)

HPW
Posts: 1390
Joined: Thu Sep 26, 2002 9:15 am
Location: Germany
Contact:

Post by HPW »

I used this:

(setq inputstring (read-file in-file))
(setq inputlist (parse inputstring "\r\n"))
(dolist(linestr inputlist)
...)

The parse pattern may vary from platform from "\r\n" to "\n".

Depends on if you need the whole file in a list or if you can
process each line seperatly. Reading whole file give speed
but cost memory.
Hans-Peter

Maurizio
Posts: 52
Joined: Mon Jul 28, 2003 3:06 pm
Location: Italy

Post by Maurizio »

Thank you very much
Maurizio

Sammo
Posts: 180
Joined: Sat Dec 06, 2003 6:11 pm
Location: Loveland, Colorado USA

Post by Sammo »

HPW's solution can be reduced to a single line:

Code: Select all

(setq inputlist (parse (read-file in-file) "\r\n"))

eddier
Posts: 289
Joined: Mon Oct 07, 2002 2:48 pm
Location: Blue Mountain College, MS US

Post by eddier »

I'm always having to work with reports. A nice thing about newLISP is the fact I can read and parse a tab delimited file exported from Excel, Access, whatever in a one liner:

Code: Select all

(setq data (map (fn (x) (parse x "\t")) (replace "\r" (parse (read-file in-file) "\n"))))
Note that with (replace "\r" (parse ... I don't have to worry if the file came from UNIX/LINUX :) or Windoze :(

Eddie

Locked