PHP文件读写

fopen的第一个输入为文件名,第二个输入确定工作方式:

'r'从起始地址开始读

'r+'起始地址开始读并且允许写入

'w'从起始地址开始只写(覆盖)

'w+'读和写也是起始地址开始

'a'附加到文件最后只写

'a+'附加到文件最后并且允许读写

创建临时文件

//创建了一个临时文件
$temp = tmpfile();
// 回到文件头
rewind($temp);
// 读取文件内容
$contents = fread($temp, 2048);    //读取文件内容

文件读写代码

";
	$hexstring = sprintf("%d %f %X", 65, 128, 231);
	echo $hexstring;
	
	echo "
"; echo time(); echo "
"; echo time() + 7 * 24 * 60 * 60; echo "
"; echo mktime(0, 0, 0, 1, 1, 2000) . "
"; //echo data("Y-m-d\TH:i:sP", time()); echo "
"; echo "fopen测试建立文件,没有文件则创建文件" . "
"; echo "fopen的第一个输入为文件名,第二个输入确定工作方式:'r'从起始地址开始读,'r+'起始地址开始读并且允许写入,'w'从起始地址开始只写(覆盖),'w+'读和写也是起始地址开始,'a'附加到文件最后只写,'a+'附加到文件最后并且允许读写" . "
"; $fh = fopen("testfile.txt", 'a+') or die("Failed to create file"); echo "
"; echo "flock:使读写只能一个线程使用,LOCK_EX执行、LOCK_UN结束" . "
"; echo " 下面的fgets和file_get_contents也只能是第一个命令运行" . "
"; flock($fh, LOCK_EX); echo "
"; echo "fgets:只读一行文件" . "
"; $text = fgets($fh) or die("并没有文件内容,我怎么读"); echo $text . "
"; $text = fgets($fh) or die("并没有文件内容,我怎么读"); echo $text . "
"; echo "
"; echo "file_get_contents:读全部文件,但使用flock后只能第一个命令读取" . "
"; echo file_get_contents("testfile.txt") . "
";; echo "
"; echo "写入文件:fwrite(\$fh, \"写入文件用fwrite\") or die(\"Could not write to file\");" . "
"; fwrite($fh, "写入文件用fwrite\r\n") or die("Could not write to file"); flock($fh, LOCK_UN); echo "关闭文件fclose" . "
"; fclose($fh); echo "
"; //$text = <<<_END line 1 line 2 line 3 _END; echo "打开文件前判断文件是否存在:file_exists(\"testfile.txt\")" . "
"; if(file_exists("testfile.txt")) { echo "File exists" . "
"; } echo "
"; echo "使用copy拷贝文件" . "
"; copy('testfile.txt', 'testfile2.txt') or die("Could not copy file"); echo "
"; echo "使用rename重命名文件" . "
"; if(!rename('testfile2.txt', 'testfile2.new')) echo "Could not rename file" . "
"; else echo "File successfully renamed to 'testfile2.new'" . "
"; echo "
"; echo "使用unlink删除文件" . "
"; if(!unlink('testfile2.new')) echo "Could not delete file" . "
"; else echo "File 'testfile2.new' successfully deleted" . "
"; //move_uploaded_fileg更新加载的文件 ?>

你可能感兴趣的:(网站,开发语言,php,文件,读取文件,写入文件)