added error handling for fread and fwrite