Sort of (it C code), I don't have it with me though and I can't remember the detail that the example goes into.
If you don't already have it, Amit Singh's Mac OSX Internals is great for this type of info.
-dave
EDIT: The other option is to go grab the source code to top and see how they do it
EDIT 2: Your -l argument is the problem. Change it from 0 to 1. The issue is that with 0, it keeps outputting and redirections don't like that. If that is what you really want (e.g. so you aren't constantly running the top command), then execute the command through a file handle and run it through a select loop to process the data.