Move file opening out of C code and reveal only close and write actions.

When I started this I planned to use drainOutput but it was found to
be unsuitable because it doesn't retry in cases when itimer
triggers. That's why we are using our own wrapper for tcdrain().