Master PHP’s fgetc(): Read Files & User Input One Character at a Time
This tutorial explains how to use PHP's fgetc() function to read single characters from opened files or standard input, covering file opening with fopen(), reading loops, handling end‑of‑file, and practical code examples for both file and user input scenarios.
In PHP there are many file‑handling functions, and fgetc() is one that reads a single character from an opened file and moves the pointer to the next position. This article introduces the usage of fgetc() and provides examples to help readers understand and apply the function.
Before using fgetc(), you need to open a file with fopen(). Example:
$file = fopen("example.txt", "r");
if ($file) {
// file opened successfully
// perform other file operations
} else {
echo "无法打开文件!";
}After successfully opening the file, you can read a character using fgetc(). The syntax is: fgetc($file) Here $file is a pointer to the opened file resource. The following example reads the file character by character and outputs each one:
$file = fopen("example.txt", "r");
if ($file) {
while (($char = fgetc($file)) !== false) {
echo $char;
}
fclose($file);
} else {
echo "无法打开文件!";
}The while loop reads each character until fgetc() returns false, indicating the end of the file. fgetc() can also read a character from user input. Example:
echo "请输入一个字符: ";
$input = fgetc(STDIN);
switch ($input) {
case 'a':
echo "您输入了字母a";
break;
case 'b':
echo "您输入了字母b";
break;
case 'c':
echo "您输入了字母c";
break;
default:
echo "您输入的字符无效";
}In this example, fgetc() reads a character from STDIN, stores it in $input, and a switch statement handles the input accordingly.
In summary, fgetc() is a PHP function for reading a single character from a file or from user input. The provided examples demonstrate correct usage for both scenarios, helping developers perform file operations and interactive character input more effectively.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
