Fixed file writing error checking