Search code examples
common-lisplispworks

Reading files common lisp


I'm a newbie in common lisp, i want to do some (maybe advanced file reading)

so lets say i have example1.txt, example2.txt and example3.txt.

example1.txt has the following:

Born 9 October 1940

Died 8 December 1980 (aged 40)

John Winston Ono Lennon, MBE (born John Winston Lennon; 9 October 1940 – 8 December 1980) was an English musician, singer and songwriter who rose to worldwide fame as a founder member of the Beatles

so what i want to do is:

i get prompted to enter a name, I enter Lennon.

if the file contains the word lennon, keep reading, else read example2, I don't know how to use the buffer in LISP, in C++ or perl, that'd be so easy for me and wouldn't had asked this question, but i have to do it in lisp. I want to return the index of the element as well so for example, if i typed "musician" i want it to continue reading, and not to start from 0.

according to this book i may need a function called READ-SEQUENCE is that true? and how to use it? by the way, I'm on windows and using LispWorks.


Solution

  • (defun find-word-in-file (word file)
      (with-open-file (stream file)
        (loop
           :for line := (read-line stream nil nil)
           :for found := (and line (search word line))
           :until (or (not line) found)
           :summing (length line) :into position
           :finally (return (when found (+ position found))))))
    
    (find-word-in-file "Lennon" "./example.txt")
    
    ;; 79
    

    Something like this would do, I guess.