Add error checking on file I/O

fixes #5511