File handling is one of the most important task in any software project. Reading data from the files and writing data to the files are two of the most critical file handling tasks. In this article, the process of opening and reading a file has been explained.
Create a file named “textdoc.txt” and add the following lines of text in that file.
Now to read the above text file the fopen and fread functions are used. Have a look at the following piece of code to grasp this concept.
Download the code
Run the code
In the above code, fopen function is being used to read the file. The first parameter to the fopen function is the file to read and the second parameter is the permission. Here ‘r’ stands for read only permission. In the code, if the file doesn’t exist or if we are somehow unable to open it, the scrip shall die and an appropriate message shall be sent to the client. Next, fread function is being used to read the file. The first parameter is the handler to the file and the second parameter is the size of the file. Finally after reading the file, it is being closed using fclose function.
Reading file contents line by line.
In the above code, all of the file content is being read at once and displayed on the webpage. This content can also be read line by line as shown in the following example.
"; } fclose($filetoopen); ?>
Download the code
Run the code
In the above code the fgets function is used to read the text document line by line. After each line is read it is checked whether the document has reached its end or not via feof function.