I am currently working on a project where I am reading in contents from a file, line by line. I would like to check if the file can be opened or is present before I do this. Something like checking the return contents of fopen() in C++, but in Scheme.
Thus far I have:
(define (perform action fileName . args)
(if (file-exists? fileName)
((define in-file (open-input-file fileName))
(do ((line (read-line in-file) (read-line in-file))) ((eof-object? line))
(display line)
(newline)))
(map display
(list "Unable to open " fileName " for reading\n"))
)
)
All this code does however is read in the file, line by line and attempts to check if the file exists. It however doesn't work because I get a ";Can't bind name in null syntactic environment: in-file #[reserved-name-item 13]" error.
I realize when the file is unable to be opened, an error of type condition-type:file-operation-error is signalled as per MIT Scheme Documentation; However, I am unable to figure out how to handle this exception, thus my workaround.
Any help would be greatly appreciated.
You have one issue with the code. You can't randomly add parenthesis into the code to make single expression for if
, because parentheses are function calls. To make single expression you need to use begin:
(define (perform action fileName . args)
(if (file-exists? fileName)
(begin
(define in-file (open-input-file fileName))
(do ((line (read-line in-file) (read-line in-file))) ((eof-object? line))
(display line)
(newline)))
(map display
(list "Unable to open " fileName " for reading\n"))
)
)