PHP offers many functions for file manipulation. The fgetc
function in PHP reads a single character from an already open file.
The syntax for the fgetc
function is shown below:
fgetc(resource $file): string|false
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.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 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?>
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