Exercise #7

Write a Scheme procedure, find-string-in-file, that takes two arguments -- sought, which can be any string, and file-name, which is also a string but should be the name of an existing text file. When invoked, find-string-in-file should open the file for input and search through it line by line, counting off the lines (starting from 1 for the first line of the file) and looking for lines that have a substring that exactly matches sought (in any position). Each time it finds such a line, it should reprint the entire line, preceded by its line number. When it reaches the end of the text file, it should close the port to that file and stop. (I don't care what value it returns; in particular, it is OK if the Chez Scheme version returns the #<void> value.)

For instance, if the text file frogs.txt contains the five lines

There is no frog in this file.
Frog has left the building.
-- n o   f r o g   i s   h e r e   a t   a l l --
Hence, vile frogspawn, toadchild, offspring of newt!
No frogs!  Deliver us from frogs!  Please -- no more frogs!

then the call (find-string-in-file "frog" "frogs.txt") should produce three lines of output:

1: There is no frog in this file.
4: Hence, vile frogspawn, toadchild, offspring of newt!
5: No frogs!  Deliver us from frogs!  Please -- no more frogs!

(Line 2 is not reprinted because the capital F in Frog does not match the lower-case f in frog. Line 3 is not reprinted because the letter-spaced version f r o g does not match either.)

Incidentally, this procedure can be used as a rough but handy tool for indexing a file that contains a lot of Scheme definitions:

> (find-string-in-file "(define" "/u2/stone/courses/scheme/html/writing-reals.ss")
51: (define write-real
80: (define strictly-real?
92: (define number->numeral
160: (define trunc
185: (define explode-into-digits
208: (define recover-digits-from-fraction
284: (define propagate-carry
333: (define list-of-digits?
355: (define propagate-through-list
393: (define digits->chars

Again, you may select your own test cases. Provide enough evidence to assure me that your program will work in any possible case.


This document is available on the World Wide Web as

http://www.math.grin.edu/courses/Scheme/fall-1997/exercise-7.html

created October 30, 1997
last revised December 18, 1997

John David Stone (stone@math.grin.edu)