PHP fgetc() Function: Reading Characters from Files and Standard Input
This article explains PHP's fgetc() function for reading a single character from an opened file or standard input, demonstrates how to open files with fopen(), shows example code for looping through file contents, and provides a user input example with a switch statement.
In PHP, the fgetc() function reads a single character from an open file and advances the file pointer.
Before using fgetc() , a file must be opened with fopen() . Example:
$file = fopen("example.txt", "r");
if ($file) {
// file opened successfully
// perform other file operations
} else {
echo "Unable to open file!";
}After opening the file, fgetc($file) reads one character. Its syntax is:
fgetc($file)The variable $file is a resource pointer to the opened file. The following example reads the entire file character by character and outputs each character:
$file = fopen("example.txt", "r");
if ($file) {
while (($char = fgetc($file)) !== false) {
echo $char;
}
fclose($file);
} else {
echo "Unable to open file!";
}The loop uses while to read each character until fgetc() returns false, indicating end of file.
Besides file reading, fgetc() can read a character from user input via STDIN . Example:
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 script prompts the user, captures a single character, and uses a switch statement to respond accordingly.
In summary, the fgetc() function is a PHP built‑in for reading a single character from a file or from standard input, and the examples above demonstrate its correct usage for file operations and interactive input.
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.