最近看了看文件操作类的知识,学学fwrite,fread命令,打算两个一起用,即先写入,再检查一下写入的内容,结果出bug了……………………
代码如下:
<!
DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"
>
< html >
< head >
< meta http-equiv ="Content-Type" content ="text/html; charset=utf-8" />
< title > New Document </ title >
< meta name ="author" content ="" />
< meta name ="keywords" content ="" />
< meta name ="description" content ="" />
< link rel ="stylesheet" type ="text/css" href ="" />
</ head >
< body >
</ body >
</ html >
< html >
< head >
< meta http-equiv ="Content-Type" content ="text/html; charset=utf-8" />
< title > New Document </ title >
< meta name ="author" content ="" />
< meta name ="keywords" content ="" />
< meta name ="description" content ="" />
< link rel ="stylesheet" type ="text/css" href ="" />
</ head >
< body >
<?
php
$filename = " html/cache.txt " ;
$contents = " 上联:日本是大核民族;下联:?????? " ;
$handle = fopen ( $filename , " a+ " );
fwrite ( $handle , $contents );
$contents = fread ( $handle , filesize ( $filename ));
echo $contents ;
fclose ( $handle );
?>
$filename = " html/cache.txt " ;
$contents = " 上联:日本是大核民族;下联:?????? " ;
$handle = fopen ( $filename , " a+ " );
fwrite ( $handle , $contents );
$contents = fread ( $handle , filesize ( $filename ));
echo $contents ;
fclose ( $handle );
?>
</ body >
</ html >
预期结果是文件中写入$contents,浏览器输出$contents,可结果让我大跌眼镜————
结果是浏览器无任何内容输出,记事本文件中却输入了三遍的$contents,无奈了,怎么平白无故却写入那么多,浏览器却一个也没有啊??(多少也给一个么...)
以为网友给我建议:
<?
php
$filename = " cache.txt " ;
$contents = " 上联:日本是大核民族;下联:?????? " ;
$handle = fopen ( $filename , " a+ " );
fwrite ( $handle , $contents );
$handle = fopen ( $filename , " a+ " );
$contents = fread ( $handle , filesize ( $filename ));
echo $contents ;
fclose ( $handle );
?>
$filename = " cache.txt " ;
$contents = " 上联:日本是大核民族;下联:?????? " ;
$handle = fopen ( $filename , " a+ " );
fwrite ( $handle , $contents );
$handle = fopen ( $filename , " a+ " );
$contents = fread ( $handle , filesize ( $filename ));
echo $contents ;
fclose ( $handle );
?>
有网友提建议,肯定是个能解决问题的,可没想到,自己试了一下,结果更让我的心拔凉拔凉的………………
一颗七上八下的心,终于快要见到曙光之时,又掉进了黑暗中。。。。。
终于无意间看到了指针复位的rewind()函数,猜想是不是指针的问题啊,于是试了一试。。。。
<?
php
$filename = " html/cache.txt " ;
$contents = " 上联:日本是大核民族;下联:?????? " ;
$handle = fopen ( $filename , " a+ " );
fwrite ( $handle , $contents );
rewind ( $handle ); // 在这里重置了指针
$contents = fread ( $handle , filesize ( $filename ));
echo $contents ;
fclose ( $handle );
?>
$filename = " html/cache.txt " ;
$contents = " 上联:日本是大核民族;下联:?????? " ;
$handle = fopen ( $filename , " a+ " );
fwrite ( $handle , $contents );
rewind ( $handle ); // 在这里重置了指针
$contents = fread ( $handle , filesize ( $filename ));
echo $contents ;
fclose ( $handle );
?>
试下结果——————OK!!!
总结:使用fopen()命令打开后,再使用fwrite()命令将文本写入,结果指针就到文段末尾了,结果可想而知,什么都没有输出来;rewind()将指针重置到文件起始位置,所以可以输出了!