Tuesday, 21 July 2015

PHP Files and I/o

Generally, there are 4 types of  I/O files are present in PHP that are as follows: opening , writing, reading, closing a file.

Opening a File:

The fopen() function in php is used to open files. This file require two arguments first one is the file name to be open and the next is that in which mode of the file is open.

Mode Purpose
r It Open the files for reading only and it places the file pointer at the beginning of the file.
r+ It Open the files for both reading and writing.
and it places the pointer at the beginning of the file.
w It Open the files for writing only and it places the file pointer at the beginning of the file. If files does not
exist then it attemts to create a file.
w+ It open the files for both reading and writing only and it
places the pointer at the beginning of the file.If files does not
exist then it attemts to create a file.
a It Open the files for writing only and it
places the pointer at the end of the file.
If files does not exist then it attemts to create a file.
a+ It Open the files for both reading and writing only and it
places the pointer at the end of the file.
If files does not exist then it attemts to create a file.

If  you want to open a file and  fopen() function is unable to open the specified file then it returns false.
We take a example to generate a message if the fopen() function is unable to open the selected file:

<html>
<body><?php
$file=fopen(“Hello World.txt”,”r”) or exit(“Unable to open file!”);
?></body>
</html>

When you completed the changes in the open file, it is important that you must close the php files & i/o with the fclose() function. For  fclose() function it requires a file pointer as its argument and then returns true when the closure succeeds or false if it fails.
  We take a example to generate a message if the fopen() function is unable to open the selected file:

<?php
$file = fopen(“Hello.txt”,”r”);//code to be executedfclose($file);
?>

Reading a file:

Once you open a file with fopen( ) function you can read the file with fread( ) function.The file require two arguments. These must be the file pointer and the length of the file expressed in bytes.
There are various types of function for reading a file:
  • The fgets() function is used to read a single line from a file.
  • The fgetc() function is used to read a single character from a file.

No comments:

Post a Comment