文件操作基本上跟C是一样的。
<?php
# 获取服务器的/
$doc_root=$_SERVER['DOCUMENT_ROOT'];
echo "$doc_root<br>";
$file1="$doc_root/file1.txt";
# 文件操作和C基本相同
# open for write
$fp=@fopen($file1,"wb"); # binary mode for default and more compatible
if ( !$fp ) # if it failed, php will cause a warning
{
echo "#1: cannot open file1.txt<br>";
exit;
}
flock($fp,LOCK_EX); // LOCK_EX : write lock
// LOCK_SH : read lock
// LOCK_UN : release the lock
// LOCK_NB : 防止在请求加锁时发生阻塞
fwrite($fp,"fwrite ");
fputs($fp,"fputs ");
flock($fp,LOCK_UN); // release write lock
fclose($fp);
# open for read
$fp=@fopen($file1,"rb");
if ( !$fp ) {
echo "#2: cannot open file1.txt<br>";
exit;
}
while (!feof($fp)) {
# $str=fgetcsv($fp,100," "); <-- this returns an array seperated by delimiter
$str=fgets($fp,1024); # fgets returns a line in the file,
# 1024 is the length, strlen($str)<1024
echo "$str<br>";
}
fclose($fp);
# readfile() writes the content of the file into stdout
echo "<pre>";
readfile($file1);
echo "</pre>";
# fpassthru() writes the content of the file into stdout and then close the file
echo "<pre>";
$fp=fopen($file1,"rb");
fpassthru($fp);
echo "</pre>";
# fgetc()
$fp=@fopen($file1,"rb");
if ( !$fp ) {
echo "#3: cannot open file1.txt<br>";
exit;
}
while (!feof($fp)) {
$c=fgetc($fp);
echo "$c<br>";
}
fclose($fp);
# fread()
# file_exists()
# filesize()
# unlink() <-- delete a file
if ( !file_exists($file1) ) {
echo '#4: '.$file1.' not found.<br>';
exit;
}
$size=filesize($file1);
$fp=fopen($file1,'rb');
$str=fread($fp,$size);
echo "<pre>$str</pre>";
fclose($fp);
unlink($file1); // delete file1.txt
if ( !file_exists($file1) ) {
echo '#5: '.$file1.' not found.<br>';
exit;
}
?>














































































