1.fopen函数:打开文件,打开时需要指定打开模式
打开模式:
r :只读方式打开
r+ :读写方式打开,在内容前边写入,并且会覆盖之前内容
$path = './test.txt';
function test_file($path){
$res = fopen($path,'r+');//读写方式打开
fwrite($res,'嘿嘿哈哈');//文件开头写入
fclose($res);//关闭文件,此处需要重新关闭再打开读取最新数据
$info = fopen($path,'r');//只读方式打开
$content = fread($info,filesize($path));//第二个参数必须写
fclose($info);
echo $content;
}
test_file($path);
w:只写方式打开
w+ :读写方式
$path = './test.txt';
function test_file($path){
$res = fopen($path,'w');//读写方式打开,如果路径下没有该文件,会创建文件
fwrite($res,'小云云');//先清空文件内容,再写入新数据
fclose($res);//关闭文件,此处需要重新关闭再打开读取最新数据
$info = fopen($path,'r');//只读方式打开
$content = fread($info,filesize($path));//第二个参数必须写
fclose($res);
echo $content;
}
test_file($path);
a:追加
a+ 读/追加
$path = './test.txt';
function test_file($path){
$res = fopen($path,'a');//追加,如果路径下没有该文件,会创建文件
fwrite($res,'小云云');//末尾写入新数据
fclose($res);//关闭文件,此处需要重新关闭再打开读取最新数据
$info = fopen($path,'a+');//读/追加
$content = fread($info,filesize($path));//第二个参数必须写
fclose($res);
echo $content;
}
test_file($path);
x
x+
$path = './test.txt';
function test_file($path){
$res = fopen($path,'x+');//读写,创建文件,如果有该文件则返回false
fwrite($res,'小云云');//写入新数据
fclose($res);//关闭文件,此处需要重新关闭再打开读取最新数据
$info = fopen($path,'r');//读/追加
$content = fread($info,filesize($path));//第二个参数必须写
fclose($res);
var_dump($content);
}
test_file($path);
2.写入函数 : fwrite() fputs() ,用法一样
3.读取函数:
fread( int handle [,int length]) :读取length长的数据
fgets( int handle [,int length]) :fgets() 从 handle 指向的文件中读取一行并返回长度最多为 length-1 字节的字符串。
fgetc( resource handle ):用于逐字读取文件数据,直到文件结束。
4.关闭文件函数
fclose()
5.不需要fopen()打开的函数
file_get_contents()
file_put_contents()
$path = './test.txt';
function test_file($path){
file_put_contents($path,'云云和航航');
$res = file_get_contents($path);
var_dump($res);
}
test_file($path);
6.访问远程文件:开启allow_url_fopen,http协议只能进行只读。ftp协议可以使用只读或者只写
7.目录操作函数
名称相关:basename()、dirname()、pathinfo()
目录读取:opendir()、readdir()、closedir()、rewinddir()
目录删除:rmdir()
目录创建:mkdir()
文件大小:filesize()
目录大小:disk_free_space()、disk_total_space()
文件拷贝:cpoy()
删除文件:unlink()
文件类型:filetype()
重命名文件或者目录:rename()
文件截取:ftruncate()
笔试题1:往文件头部输入hello world
//思路:
//1.打开文件
//2.取出文件内容
//3.在内容头部拼接内容
//4.将内容写入文件
$path = './test.txt';
function WriteToFile($path){
$file = fopen($path,'r+');//只读方式打开文件
$content = fread($file,filesize($path));
$content = '小航和'.$content;
fclose($file);
$filew = fopen($path,'w');
fwrite($filew,$content);
fclose($filew);
}
WriteToFile($path);
笔试题2:循环目录文件,用到了递归
$path = './test';
function loopDir($path){
//1.打开目录
$handler = opendir($path);
//2.读取文件名(排除文件名为0的和'.' '..')
while(false != ($file = readdir($handler))){
if($file != '.' && $file != '..'){
echo $file.'<br/>';
//如果是文件夹,进入递归
if(filetype($path.'/'.$file) == 'dir'){
loopDir($path.'/'.$file);
}
}
}
}
loopDir($path);