Using PHP fgetc() to Read Characters from Files and User Input
This article explains the PHP fgetc() function, showing how to open a file with fopen(), read characters sequentially, handle end‑of‑file, and also capture single‑character user input from STDIN with practical code examples.
The PHP fgetc() function reads a single character from an opened file and advances the file pointer to the next character.
Before using fgetc() , you must open a file with fopen() . Example:
$file = fopen("example.txt", "r");
if ($file) {
// File opened successfully
// Perform other file operations
} else {
// File opening failed
echo "Unable to open file!";
}After successfully opening the file, you can call fgetc() to read one character. The syntax is:
fgetc($file)Here $file is the file resource pointer. A typical loop to read the entire file character by character looks like this:
$file = fopen("example.txt", "r");
if ($file) {
while (($char = fgetc($file)) !== false) {
echo $char;
}
fclose($file);
} else {
echo "Unable to open file!";
}The while loop continues until fgetc() returns false , indicating the end of the file.
Beyond file reading, fgetc() can also read a single character from user input (STDIN). The following example demonstrates this and uses a switch statement to react to the input:
echo "Please enter a character: ";
$input = fgetc(STDIN);
switch ($input) {
case 'a':
echo "You entered the letter a";
break;
case 'b':
echo "You entered the letter b";
break;
case 'c':
echo "You entered the letter c";
break;
default:
echo "Invalid character entered";
}This example shows how fgetc() captures a character from the user, stores it in $input , and then processes it with a switch statement.
In summary, the PHP fgetc() function is a simple way to read single characters from files or interactive input, and the provided examples illustrate its correct usage for both scenarios.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.