Home  >  Article  >  Backend Development  >  The Complete Manual of PHP - File System

The Complete Manual of PHP - File System

巴扎黑
巴扎黑Original
2016-12-01 10:26:201329browse

1.  目录操作

$dir="C:";  
if(is_dir($dir)){       验证路径的有效性  
    $dir_res=opendir($dir);         返回一个资源对象,用于存储当前的目录资源  
    while($filen=readdir($dir_res)){    读取目录中的文件  
        echo $filen."<br>";  
    }     
    closedir($dir_res);关闭目录  
}     
else   
    echo "目录不存在!";  
  
$dir2="Test/";  
if(!is_dir($dir2)){  
    mkdir($dir2);  创建目录  
}  
if(is_dir($dir2)){  
    rmdir($dir2);  删除目录  
}

 2. 文件读取  

$path="Test\\1.txt";  
$filesize=filesize($path);#获取文件的长度  
$file=fopen($path, "r");#打开文件  
echo $filesize."字节<br>";  
echo fgetc($file)."<br>";#读取一个字符,  
echo fgetc($file)."<br>";#读取后指针下移  
echo fgets($file)."<br>";#从指针出开始读取一行  
echo fgets($file)."<br>";  
echo fread($file, $filesize);   #从指针出开始读取指定长度的字符串  
fclose($file);

 

3. 文件写入  

$path="Test\\1.txt";  
$filesize=filesize($path);#获取文件的长度  
$file=fopen($path, "w");  
fwrite($file, "Hello World!\n",20);#写入的字符串,要写入的长度  
fwrite($file, "This is a test!\n");  
fclose($file);  
  
unlink($path);#删除文件

4. fopen文件时,若文件不存在,则自动创建该文件  

$path="DB/";  
$filename="S".date("YmdHis").".dat";  
$fp=fopen($path.$filename, "w");


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:View file sizeNext article:View file size