How To Read One Character from a File


How To Read One Character from a File? - PHP Script Tips - Reading and Writing Files



If you have a text file, and you want to read the file one character at a time, you can use the fgetc() function. It reads the current character, moves the file pointer to the next character, and returns the character as a string. If end of the file is reached, fgetc() returns Boolean false. Here is a PHP script example on how to use fgetc():

$file = fopen("/windows/system32/drivers/etc/services", "r");
$count = 0;
while ( ($char=fgetc($file)) !== false ) {
  if ($char=="/") $count++;
print("Number of /: $count\n");

This script will print:

Number of /: 113

Note that rtrim() is used to remove "\n" from the returning string of fgets().

2007-04-22, 4818👍, 0💬