Java Techies- Solution for All
File
There are following steps involve in File manipulation :
- Open the file for read or write.
- Read the file.
- Close the file.
- Perform operations on the file content.
- Print the result.
Modes | Description |
---|---|
r | Read only at the beginning of the file. |
r+ | Read or Write at the beginning of the file |
w | It will create a new file if it does not exist and if exist it erase the contents of any file of this name before writing. |
w+ | Read and Write if the file doesn't exist so it will create a file of this name, and if exist it will erase the contents of any file of this name before writing. |
a | Append,use to open and write to the end of the file if exist. |
a+ | Read and Write to the end of the file if exist. |
Open the file
fopen()
: This function is used to open the files in PHP. Example :
<?php $file=fopen("D:\tkhts\id.txt","r") or exit("Unable to open file!"); ?>
Closing the File
fclose()
:This function is used to close an open file.
Example :
<?php $file = fopen("D:\tkhts\id.txt","r"); //code executed fclose($file); ?>
End-of-file
feof
:This function checks end-of-file on a file pointer and takes a
filename as argument and it is used in a while loop to perform the
same task(function) on each line in a file.
Syntax :
while(!feof($f)) { $val=fgets($f); echo "val"; echo"end of file"; }
Read the file
fgets()
:This function is used to read a single line from a file in PHP.
fgetc()
:This function is used to read a single character from a file.
Example1 :
<?php $f = fopen("D:\tkhts\id.txt", "r") or exit("Unable to open file!"); while(!feof($f)) { echo fgets($f). "<br>"; } fclose($f); ?>
Output :
Learn PHP from : www.tkhts.com
Example 2:
<?php $file=fopen("D:\tkhts\id.txt","r") or exit("Unable to open file!"); while (!feof($f)) { echo fgetc($f)."<br>"; } fclose($f); ?>
Output :
L e a r n P H P f r o m : w w w . t k h t s . c o m