Thursday, November 10, 2011

File Handling

PHP file functions reference : http://www.w3schools.com/php/php_ref_filesystem.asp


Open a file
$file=fopen("welcome.txt","r") or exit("Unable to open file!");


ModesDescription
rRead only. Starts at the beginning of the file
r+Read/Write. Starts at the beginning of the file
wWrite only. Opens and clears the contents of file; or creates a new file if it doesn't exist
w+Read/Write. Opens and clears the contents of file; or creates a new file if it doesn't exist
aAppend. Opens and writes to the end of the file or creates a new file if it doesn't exist
a+Read/Append. Preserves file content by writing to the end of the file
xWrite only. Creates a new file. Returns FALSE and an error if file already exists
x+Read/Write. Creates a new file. Returns FALSE and an error if file already exists

 If the fopen() function is unable to open the specified file, it returns 0 (false).

Closing a File
fclose($file);

Check for End of the file
if (feof($file)) echo "End of file";
You cannot read from files opened in w, a, and x mode!

fgets() : Read Line by Line
$file = fopen("welcome.txt", "r") or exit("Unable to open file!");
//Output a line of the file until the end is reached
while(!feof($file))
  {
  echo fgets($file). "<br />";
  }
fclose($file);

After a call to this function the file pointer has moved to the next line.

fgestc() : Read character by character
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
while (!feof($file))
  {
  echo fgetc($file);
  }
fclose($file);

After a call to this function the file pointer has moved to the next character.

No comments:

Post a Comment