1--TEST-- 2Test fscanf() function: error conditions 3--FILE-- 4<?php 5echo "*** Testing fscanf() for error conditions ***\n"; 6$file_path = __DIR__; 7 8$filename = "$file_path/fscanf_error.tmp"; 9$file_handle = fopen($filename, 'w'); 10if ($file_handle == false) 11 exit("Error:failed to open file $filename"); 12fwrite($file_handle, "hello world"); 13fclose($file_handle); 14 15// invalid file handle 16try { 17 fscanf($file_handle, "%s"); 18} catch (TypeError $e) { 19 echo $e->getMessage(), "\n"; 20} 21 22// number of formats in format strings not matching the no of variables 23$file_handle = fopen($filename, 'r'); 24if ($file_handle == false) 25 exit("Error:failed to open file $filename"); 26try { 27 fscanf($file_handle, "%d%s%f", $int_var, $string_var); 28} catch (ValueError $exception) { 29 echo $exception->getMessage() . "\n"; 30} 31fclose($file_handle); 32 33// different invalid format strings 34$invalid_formats = array( $undefined_var, 35 "%", "%h", "%.", "%d%m" 36 ); 37 38 39// looping to use various invalid formats with fscanf() 40foreach($invalid_formats as $format) { 41 $file_handle = fopen($filename, 'r'); 42 if ($file_handle == false) 43 exit("Error:failed to open file $filename"); 44 try { 45 var_dump(fscanf($file_handle, $format)); 46 } catch (ValueError $exception) { 47 echo $exception->getMessage() . "\n"; 48 } 49 fclose($file_handle); 50} 51 52echo "\n*** Done ***"; 53?> 54--CLEAN-- 55<?php 56$file_path = __DIR__; 57$filename = "$file_path/fscanf_error.tmp"; 58unlink($filename); 59?> 60--EXPECTF-- 61*** Testing fscanf() for error conditions *** 62fscanf(): supplied resource is not a valid File-Handle resource 63Different numbers of variable names and field specifiers 64 65Warning: Undefined variable $undefined_var in %s on line %d 66array(0) { 67} 68Bad scan conversion character " 69Bad scan conversion character " 70Bad scan conversion character "." 71Bad scan conversion character "m" 72 73*** Done *** 74