added error handling on fclose and fwrite.