php学习笔记5—(文件操作)

文件操作基本上跟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 ;
    }
?>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值