오충현
오충현

Reputation: 17

How to read file and save data On LISP programming language

I have a question about LISP Programming language

What I have to do is read a file and save data in the file.

To do this, I found the function like this and executed it.

(defun get-file (pathname)
  (with-open-file (stream pathname)
    (loop for line = (read-line stream nil)
          while line
          collect line)))

get-file("sample.txt")

This printed "unbound variable". Why did the error happened? (If I just defined the function and compiled, there was no error)

How do I write the pathname correctly? (My data file (sample.txt) is in the same directory of LISP code file.)

And where the data had saved?

And how I can divide them (because the file is read line by line, the data with seperate attributes should be save in same line)

file data are saved like this

name 23.0 22 123 33  //(one string and four numbers)
name2 23.5 11 156 42 //(one string and four numbers)
name3 21.7 15 167 55 //(one string and four numbers)

Please help me I'am awkward in LISP Language because I'm fully adapted in C Language :(

Thanks a lot!!

Upvotes: 0

Views: 1240

Answers (1)

Sylwester
Sylwester

Reputation: 48745

get-file 
("sample.txt")

Are two expressions.. One that evaluates the variable get-file since it is not used as a function. Then you have the expression ("sample.txt") which tries to take the string "sample.txt" and call it as if it was a function with no arguments.

The reason for this is that you are writing algol syntax, as if it was C or Java. You need to write lisp syntax when you are writing lisp, like this:

(get-file "sample.txt")

The path name is relative to the path you start the program so if you start the program from the same directory as you lisp file it will open files there. If you were at your home directory the path is relative to that unless you use absolute path.

In order to save data you need to open a file to save to and output to that file. How it is now you just make a list of the lines and that is returned no screen in the REPL.

You may split the string by space. You can convert the strings that represent numbers to numbers by using parse-number. An unsafe way would be (read-from-string "3.0") ; ==> 3.0

You need to prepare yourself to learn a new language. It has different syntax than C, which is based on Algol. Almost all programming languages today are so if you know several languages you know perhaps several dialects of the same language. Give it time and you'll have a new favorite programming language soon..

Upvotes: 1

Related Questions