Recursion with files

Course links

Exercise 1

If you have the definition of port-copy in a DrScheme definitions window, what expression would you add after this definition to complete a program that has the same effect as the shell command cp original duplicate?

Hint: The answer is not
(port-copy "original" "duplicate")

since "original" and "duplicate" are strings and not ports. Think about how to satisfy the preconditions for port-copy and the post-conditions for the whole operation.

Exercise 2

Adapt the port-copy procedure so that it copies only letters and whitespace characters to the output port, discarding all the punctuation and numeric characters.

Exercise 3

Let's say that the complement of the character in position n in the ASCII character set is the character in position 127 - n. (For example, the complement of the capital Y, which is in position 89, is the ampersand, &, which is in position 38.) Adapt either version of the copying program so that, instead of echoing each character from the source file into the target file without change, the program replaces each character with its complement, producing an encrypted file.

Exercise 4

Develop an input port operation port-size that reads characters one at a time through a given port until it encounters the end-of-file object, then returns the number of characters read (not including the end-of-file object).

Exercise 5

Use port-size and call-with-input-file to determine how many characters are in the file /home/stone/courses/scheme/examples/sample.dat.

Exercise 6

Using the read-line procedure defined in the reading on files, develop a Scheme procedure line-lengths that takes as arguments an input port and an output port, reads a line at a time from the input port, and writes to the output port the length of each line that it reads (i.e., the number of characters on that line, including the newline character that terminates the line).

Since read-line never returns the end-of-file object, you'll have to identify the base case for your file recursion differently in defining line-lengths. (Hint: Use peek-char.)

Did you begin by thinking of some sample calls to the procedure you're trying to write, to use as test cases? (If not, you may have had unnecessary trouble with this exercise.) Implement and run your test cases now.

I am indebted to Professor Ben Gum for his contributions to the development of this lab.