一般文件处理的三个步骤:
①打开文件,如果该文件不存在,创建文件;
②对数据进行读写操作;
③关闭该文件;
1、打开文件:
fopen( 文件路径,打开模式);
2、写文件:
fwrite( string filename,string data, [int flags],[resource context] );
如:fwrite($fp,$outputstring,strlen($outputstring)) //$outstring写入$fp;
3、读取文件:
1)文件读取结束函数:
feof( );
2)每次读取一行数据:
fgets( ):一般读取一行数据fget($fp,999);
fgetss(resource fp,int length,[string allowable_tags]):过滤字符串中的php和html标准读取;
fgetcsv(resource fp,int length,[string delimiter],[string enclourde]):重定义输出流定界符;
3)读取整个文件:(调用后会自动关闭文件)
readfile(string url):全文从文件头读取,标准流输出(输出到浏览器),很多场合可以取代fopen;
boolean
fpassthru(string filename ):将文件指针作为参数将文件内容发送到标准输出,要先用fopen打开文件);
file( string url):全文从文件头读取,以数组形式输出;
file_get_contents(string url ):全文从头读取,字符串形式输出;
4)只读取一个字符:
fgetc( );
5)读取任意长度:string
fread(resource fp,int length),字符串形式输出;
6)查看文件是否存在:
file_exists( )
7)确定文件大小:
filesize( )
8)删除一个文件:
unlink( )
9)在文件中定位:
rewind( ):文件指针复位到文件头;
fseek( ):调整文件指针位置;
ftell( ):以字节为单位报告文件指针位置;
10)文件锁:
flock( ): LOCK_SH:读操作锁定,共享锁定;
LOCK_EX:写操作锁定,文件不共享;
LOCK_UN:释放文件锁;
4、关闭文件:
fclose($a)
php读写文件示例代码:
try{
//打开文件,并检测文件是否可以打开,
$fp = @ fopen("orders.txt","ab"); //使用@抑制自带的错误抛出,通过try/catch块抛出捕获异常自定义抛出的异常提示
if(!$fp)
throw new fileOpenException();
//对文件访问加互斥锁
$lock = @ flock($fp,LOCK_EX);
if(!$lock)
throw newfileLockException ();
//向文件写入
$wrote = fwrite($fp, $outputing,strlen($outputing);
if(!wrote)
throw new fileWriteException();
//从文件读取
$file_string = fgets(999); //读取一行
//对文件的操作结束后,解锁
flock(@fp,LOCK_UN);
//关闭文件数据流
fclose($fp);
echo "<p>Order written</p>";
}
catch(fileOpenException $ex){
echo "<p><strong>".$ex."</strong></p>";
}
catch(fileLockException $ex){
echo "<p><strong>".$ex."</strong></p>";
}
catch(fileWriteException $ex){
echo "<p><strong>".$ex."</strong></p>";
}
catch(Exception $ex){
echo "<p><strong>Your order could not be processed at this time.Please try again later</strong></p>";
}