Mastering PHP’s fgetc(): Read Files and User Input One Character at a Time

This guide explains how to use PHP’s fgetc() function to open a file, read its contents character by character, and capture user input from the command line, complete with clear code examples and best‑practice tips.

php Courses
php Courses
php Courses
Mastering PHP’s fgetc(): Read Files and User Input One Character at a Time

In PHP, the fgetc() function reads a single character from an opened file and moves the file pointer forward. This article introduces the usage of fgetc() and provides examples to help readers understand and apply the function effectively.

Before using fgetc(), you must open a file with fopen(). Example:

$file = fopen("example.txt", "r");
if ($file) {
    // file opened successfully
    // perform other file operations
} else {
    // file opening failed
    echo "无法打开文件!";
}

After successfully opening the file, you can read a character using fgetc(). The syntax is: fgetc($file) Here $file is the file resource pointer. 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 "无法打开文件!";
}

The while loop continues until fgetc() returns false, indicating the end of the file.

Besides reading from files, fgetc() can also read a single 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 "您输入的字符无效";
}

This script captures a character from the command line, stores it in $input, and uses a switch statement to respond accordingly.

In summary, the fgetc() function is a simple yet powerful tool for reading single characters from files or user input in PHP. Understanding its usage enables more precise file manipulation and interactive command‑line programs.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Code Examplebackend-developmentfile-handlingfgetcUser 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

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.