Fix a potential file descriptor leak.

Found by cppcheck.
Fix unsafe use of strncpy() and sprintf().

The strncpy() problem was found by cppcheck.