What is fgetc in PHP?
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.fileis 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
fgetcfunction is not optimized for large files, as it only reads one character at a time.
Code
The following code shows how we can use the fgetc function in PHP.
<?php$file = fopen("test.txt","r"); // open the fileecho 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.
Free Resources