PHP | fgets( ) Function
The fgets() function in PHP is an inbuilt function which is used to return a line from an open file.
- It is used to return a line from a file pointer and it stops returning at a specified length, on end of file(EOF) or on a new line, whichever comes first.
- The file to be read and the number of bytes to be read are sent as parameters to the fgets() function and it returns a string of length -1 bytes from the file pointed by the user.
- It returns False on failure.
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 file pointed by the user or False on failure.
Errors And Exceptions
- The function is not optimised for large files since it reads a single line at a time and it may take a lot of time to completely read a long file.
- The buffer must be cleared if the fgets() function is used multiple times.
- The fgets() function returns Boolean False but many times it happens that it returns a non-Boolean value which evaluates to False.
Suppose there is a file named “gfg.txt” which consists of :
This is the first line.
This is the second line.
This is the third line.
Program 1
<?php // file is opened using fopen() function $my_file = fopen("gfg.txt", "rw"); // Prints a single line from the opened file pointer echo fgets($my_file); // file is closed using fclose() function fclose($my_file); ?> |
Output:
This is the first line.
Program 2
<?php //file is opened using fopen() function $my_file = fopen("gfg.txt", "rw"); // prints a single line at a time until end of file is reached while (! feof ($my_file)) { echo fgets($my_file); } // file is closed using fclose() function fclose($my_file); ?> |
Output:
This is the first line. This is the second line. This is the third line.
Reference:
http://php.net/manual/en/function.fgets.php
Recommended Posts:
- PHP | SplFileObject fgets() Function
- How to call a function that return another function in JavaScript ?
- How to get the function name inside a function in PHP ?
- How to get the function name from within that function using JavaScript ?
- PHP | Ds\Map get() Function
- PHP | end() Function
- D3.js | d3.map.set() Function
- PHP | max( ) Function
- D3.js | d3.min() function
- PHP | min( ) Function
- CSS | rgb() Function
- D3.js | d3.rgb() Function
- p5.js | str() function
- p5.js | int() function
- CSS | var() Function
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



