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 PHP 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() . The following example demonstrates opening 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!";
}

After successfully opening the file, you can read characters using fgetc() . The syntax is:

fgetc($file)

Here $file is the resource pointer returned by fopen() . The example below reads the file character by character and echoes each character until the end of the file:

$file = fopen("example.txt", "r");
if ($file) {
    while (($char = fgetc($file)) !== false) {
        echo $char;
    }
    fclose($file);
} else {
    echo "Unable to open file!";
}

The while loop continues until fgetc() returns false , indicating that all characters have been read.

In addition to reading from files, fgetc() can read a single character from user input via STDIN . The following example prompts the user for a character and uses a switch statement to respond accordingly:

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";
}

This demonstrates how fgetc() captures user input, stores it in $input , and allows conditional logic based on the entered character.

In summary, the fgetc() function is a useful PHP tool for reading single characters from files or standard input, and the provided examples illustrate its correct usage in both contexts.

php8, here I come

Scan the QR code to receive free learning materials

PHPfile handlingfgetcSTDINcharacter reading
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.