Using PHP fgetc() to Read Characters from Files and Standard Input
This article explains PHP's fgetc() function for reading single characters from files or standard input, demonstrates opening files with fopen(), shows example code for looping through file contents, and provides a user input example with a switch statement, helping readers master character-level file operations.
The fgetc() function in PHP reads a single character from an opened file pointer and moves the pointer to the next character. This guide introduces the usage of fgetc() and provides examples to help readers understand and apply the function.
Before using fgetc() , a file must be opened with fopen() . The following example demonstrates opening a file for reading:
$file = fopen("example.txt", "r");
if ($file) {
// File opened successfully
// Perform other file operations
} else {
// File failed to open
echo "Unable to open file!";
}After successfully opening the file, fgetc() can be used to read one character at a time. Its syntax is:
fgetc($file)Here $file is a pointer to the opened file resource. The following example reads the file content 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!";
}In this example, a while loop reads each character until fgetc() returns false , indicating the end of the file.
Beyond file reading, fgetc() can also read a character from user input. The following code prompts the user, reads a character from STDIN , and uses a switch statement to act on 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 single character from the user, stores it in $input , and then processes it with a switch statement.
In summary, the fgetc() function is a PHP tool for reading one character from a file or from standard input. The provided examples illustrate correct usage for file content reading and interactive character input, enabling developers to perform fine‑grained file operations and user interactions.
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.