Added check for file writing to avoid errors.