Pages

Saturday, October 30, 2010

Passing code as a text stream into a program

A text stream is a line of text terminated by the newline character, '\n'. The standard library function getchar() retrieves one character at a time from the text stream. 


In the first chapter of Kernighan and Ritchie's The C Programming Language 2e, this function is used in programs of increasing complexity, from a character counter to a rudimentary syntax checker. 


Testing these programs in Xcode's Debugger Console can only be very limited. As soon as the user presses Enter, the text stream is happily processed, and the program expects additional input. But what if you want to test input spanning multiple lines?




In K&R C section 1.6, the first example program counts the frequency of different characters, like digits and blanks. Sample output is from "the program on itself." Near the end of the chapter, Exercise 1-23 asks to "write a program to remove all comments from a C program." There has to be some way to pre-populate the text stream, so that your program processes it to an EOF. 


Using cat, we can pipe the output of a file, such as main.c, to our program. Since we're using Xcode, the path to our project directory can be pretty long to type every time. Instead, we'll write an AppleScript script to tell Xcode to build the project, and to tell Terminal to activate and execute the cat pipe:





The script uses some parts from my previous AppleScript tutorial. Fortunately, all paths are POSIX formatted rather than aliases formatted as HFS paths.  


The one new thing is the use of quoted form, which lets me pass a directory with spaces, like /Programming Exercises/, without escaping the blanks.


With this script, the same program now processes a text stream all the way to EOF:



And the output:




I'm not sure how much use this will be beyond the first chapter, but now that I can pass text streams to EOF in my programs, I feel better about going through these exercises. Instead of one-liner "tests," I can pass whole files as representative input.


References

No comments:

Post a Comment