Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

php

What is fgetc in PHP?

Sheza Munir

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

PHP offers many functions for file manipulation. The fgetc function in PHP reads a single character from an already open file.

Syntax

The syntax for the fgetc function is shown below:

fgetc(resource $file): string|false

Parameters

The fgetc function has one parameter:

  • file: This is a required parameter. file is the name of the file stream associated with the already opened file that we will read.

Return value

The fgetc function returns a single character read from the file. If it cannot return a character due to an error or by coming to the end of the file, fgetc will return false.

The fgetc function is not optimized for large files, as it only reads one character at a time.

The working of fgetc function.

Code

The following code shows how we can use the fgetc function in PHP.

main.php
test.txt
<?php
$file = fopen("test.txt","r"); // open the file
echo fgetc($file);
echo " ";
while(!feof($file)) //checks if at end of the file
{
echo fgetc($file); //reads one character from the file
}
fclose($file); // close the file
?>

Explanation

The file test.txt is opened and associated with the file pointer $file. A single call to the function returns a single character.

Subsequent calls to the function resume from the position of the last read character and, using this function in a loop, the entire file contents can be read character by character.

RELATED TAGS

php

CONTRIBUTOR

Sheza Munir
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring