Backend Development 4 min read

Using PHP fgetc() to Read Characters from Files and User Input

This article explains PHP's fgetc() function for reading single characters from files or user input, demonstrates opening files with fopen(), shows loop-based character reading, and provides complete code examples for both file and interactive input scenarios.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP fgetc() to Read Characters from Files and User Input

In PHP there are many file‑handling functions, one of which is fgetc() . The 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 code:

$file = fopen("example.txt", "r");
if ($file) {
   // 文件打开成功
   // 执行其他文件操作
} else {
   // 文件打开失败
   echo "无法打开文件!";
}

After the file is successfully opened, you can call fgetc($file) . The syntax is:

fgetc($file)

$file is a resource pointer returned by fopen() . The following example reads a file character by character and echoes each character until false is returned, then closes the file.

$file = fopen("example.txt", "r");
if ($file) {
   while (($char = fgetc($file)) !== false) {
      echo $char;
   }
   fclose($file);
} else {
   echo "无法打开文件!";
}

The example uses a while loop; each iteration fgetc() returns a character and moves the pointer. When the end of the file is reached, fgetc() returns false and the loop ends.

fgetc() can also read a character from standard input. The next example prompts the user, reads a character with fgetc(STDIN) , and uses a switch statement to act on the input.

echo "请输入一个字符: ";
$input = fgetc(STDIN);

switch ($input) {
   case 'a':
      echo "您输入了字母a";
      break;
   case 'b':
      echo "您输入了字母b";
      break;
   case 'c':
      echo "您输入了字母c";
      break;
   default:
      echo "您输入的字符无效";
}

This demonstrates obtaining user input via fgetc() , storing it in $input , and processing it with a switch statement.

In summary, fgetc() is a PHP function for reading a single character from a file or from user input; the article provides usage syntax and several practical code snippets to help developers master file operations and interactive character input.

The article concludes with a promotional note encouraging readers to scan a QR code to receive free learning materials.

backendphpfile handlingfopenfgetcreading-input
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.