Backend Development 4 min read

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

This article explains the PHP fgetc() function, showing how to open files with fopen(), read characters sequentially using fgetc() in loops, and capture user input from STDIN, accompanied by clear code examples for each use case.

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

The fgetc() function in PHP reads a single character from an opened file and advances the file pointer to the next character.

Before using fgetc() , a file must be opened with fopen() ; the article provides a sample snippet that opens example.txt for reading and checks for success.

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

Once the file is open, fgetc() can be called to read one character at a time. Its syntax is simply fgetc($file) .

fgetc($file)

The article then demonstrates reading an entire file character‑by‑character using a while loop that continues until fgetc() returns false .

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

In this loop, each call to fgetc() returns the next character and moves the pointer forward; when all characters have been read, fgetc() returns false and the loop ends.

The function can also read a character from user input via STDIN . An example prompts the user, captures a single character with fgetc(STDIN) , and uses a switch statement to react to 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 example shows how fgetc() captures a single character from the console, stores it in $input , and then a switch statement determines the appropriate response.

In summary, fgetc() is a PHP function for reading one character from a file or from standard input, and the article provides practical examples to help readers understand and apply it correctly.

PHPfile handlingfopencharacter inputfgetcSTDIN
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.