Using PHP fgetc() to Read Characters from Files and User Input
This article explains the PHP fgetc() function, shows how to open files with fopen(), demonstrates reading characters from a file and from STDIN using loops and switch statements, and provides complete code examples for each scenario.
The fgetc() function in PHP reads a single character from an opened file pointer and advances the pointer to the next position.
Before using fgetc() , you must open a file with fopen() . The following example shows how to open 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!";
}Once the file is successfully opened, you can read a character using fgetc($file) . The syntax is:
fgetc($file)Below is an example that reads the entire file character by character using a while loop:
$file = fopen("example.txt", "r");
if ($file) {
while (($char = fgetc($file)) !== false) {
echo $char;
}
fclose($file);
} else {
echo "Unable to open file!";
}In this loop, fgetc() returns each character until it reaches the end of the file, at which point it returns false and the loop terminates.
The fgetc() function can also read a single character from user input. The following example prompts the user, reads a character from STDIN , and uses a switch statement to respond:
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";
}In this example, fgetc() captures the user's input character, stores it in $input , and the switch statement determines the appropriate response.
In summary, the fgetc() function is a useful PHP tool for reading single characters from files or user input, and the provided examples illustrate its correct usage in both contexts.
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.