php中的文件操作

<?php
//$path是文件路径:$path="text.txt";
$files1=fopen($path,'r')or die("Unable to open file!");//打开文件为只读,文件指针在文件的开头开始。

$files2=fopen($path,'r+')or die("Unable to open file!");//打开文件为读/写,文件指针在文件开头开始。

$files3=fopen($path,'w')or die("Unable to open file!");//打开文件为只写,删除文件的内容或创建一个新的文件,如果它不存在。文件指针在文件的开头开始。

$files4=fopen($path,'w+')or die("Unable to open file!");//打开文件为读/写,删除文件内容或创建新文件,如果它不存在。文件指针在文件开头开始。

$files5=fopen($path,'a')or die("Unable to open file!");//打开文件为只写,文件中的现有数据会被保留。文件指针在文件结尾开始。如果文件不存在,创建新的文件。

$files6=fopen($path,'a+')or die("Unable to open file!");//打开文件为读/写,文件中已有的数据会被保留。文件指针在文件结尾开始。如果文件不存在,创建新的文件。

$files7=fopen($path,'x')or die("Unable to open file!");//创建新文件为只写,返回 FALSE 和错误,如果文件已存在。

$files8=fopen($path,'x+')or die("Unable to open file!");//创建新文件为读/写,返回 FALSE 和错误,如果文件已存在。

?>

新建一个txt文件键入以下内容

The first line;
The second line;
The third line;

fgets() 函数用于从文件读取单行。读到行末尾,返回一个字符串

<?php
$path="text.txt";
$files=fopen($path,'r+')or die("Unable to open file!");//用读写的方式打开
while(!feof($files))
{
	$line=fgets($files);
	echo '<p>'.$line.'</p>';
}
fclose($files);
?>


fgetc() 函数用于从文件读取单字符。返回一个字符

<?php
$path="text.txt";
$files=fopen($path,'r+')or die("Unable to open file!");//用读写的方式打开
while(!feof($files))
{
	$char=fgetc($files);
	echo '<p>'.$char.'</p>';
}
fclose($files);
?>

将字符串内容写入文件,此操作是在文件指针之后进行覆盖性写入,注意字符补齐

<?php
$path="text.txt";
$txt="The fourth line;";
$files=fopen($path,'r+')or die("Unable to open file!");//用读写的方式打开
fwrite($files, $txt);//写入//The first line;
fclose($files);
?>


fclose()关闭这个文件

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值