Your ungetch has very strange behavior on error.
I'm not quite sure whether it's better or worse than On Error Resume NextOn Error Resume Next, but it's certainly in the same class.
Either handle it yourself, which means reporting an error to stderr and aborting the program, or report it to the caller (see the docs on ungetcungetc for a way).
At the moment, you print an error-message (which might get lost in the output, and anyway there's a human actively and attentively monitoring things), but then happily move on with data-loss and without informing the caller.