What is fgets() used in Reading file?
This function is used to read a single line from a file. You can pass this function a file handle corresponding to an open file, and optional length.
Why fgets() used in Reading file?
- It returns a line from a file pointer and terminates at a given length, end of file(EOF), or new line, whichever comes first.
- The
fgets()
function is passed the file to read and the number of bytes to read as arguments, and it returns a string of length -1 bytes from the file indicated by the user. - If it fails, it returns False.
Syntax:-
fgets(file, length)
Parameters Used: The fgets() function in PHP accepts two parameters. file : It specifies the file from which characters have to be extracted. length : It specifies the number of bytes to be read by the fgets() function. The default value is 1024 bytes.
Return Value : It returns a string of length -1 bytes from the user-specified file, or False if the operation fails.
Errors And Exceptions:-
- Because it reads a single line at a time, the method isn’t designed for huge files, and reading a long file can take a long time.
- If the
fgets()
method is called more than once, the buffer must be emptied. - Although the
fgets()
method returns the Boolean False, it frequently produces a non-Boolean result that evaluates to False.
Let’s take one Example:-
Suppose there is a file named “test.txt” which consists of :
This is the first line.
This is the second line.
This is the third line.
Example 1:-
Output:–
Example 2:-
Output:-