Backend Development 4 min read

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

This article explains PHP's fgetc() function, showing how to open files with fopen(), read individual characters from files or standard input, and provides complete code examples illustrating character-by-character reading and handling user input using loops and switch statements.

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

The fgetc() function in PHP reads a single character from an opened file pointer and advances the pointer to the next character, making it useful for both file processing and interactive input.

Before using fgetc() , a file must be opened with fopen() . The following example demonstrates opening a file for reading and handling potential errors:

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

Once the file is opened, fgetc() can be called to retrieve one character at a time. Its syntax is simply:

fgetc($file)

To read an entire file character by character, a while loop is typically used. The example below reads each character until fgetc() returns false , then closes the file:

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

The fgetc() function can also read a single character from standard input (STDIN). The following snippet prompts the user, reads the input character, and uses a switch statement to respond accordingly:

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

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

In summary, fgetc() is a straightforward PHP function for reading single characters from files or user input, and the provided examples illustrate its proper usage in common scenarios.

backend developmentPHPfile handlingfgetcReading Characters
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.