Home  >  Article  >  Backend Development  >  TXT 文件操作有关问题,

TXT 文件操作有关问题,

WBOY
WBOYOriginal
2016-06-13 11:58:24987browse

TXT 文件操作问题,急急急
用fwrite 写入字符串到文档里面怎么让指针停在最后一行的末尾而不是下一行啊?
每次在字符串后面加上PHP_EOL或者“\r\n”的话写完最后一行的时候,在文档里面看着是这样的
"String 1"
"String 2"
但是实际上我用fgets(代码如下)读取时

<br />$fname1=("pending.txt");<br />$fp1=fopen($fname1, "r+");<br /><br />while(!feof($fp1))<br />{	<br />	$read=explode(";", fgets($fp1));//字符串中用;来打成数组<br />	echo "read[0]= ".$read[0];// 用来测试<br />	echo "<br/>";<br />}<br />fclose($fp1);<br />

测试结果如下
read[0]= [email protected]
read[0]= [email protected]
read[0]= 
为什么多出一个呢是因为写入最后一行字符串的时候。空格了一下,在TXT 文档里面按行读取就能读取到。
如何避免这个问题呢?因为需求我必须要用fgets(),如果功能允许我用file_get_contents()就好说了。。
求大神给解决方案
------解决方案--------------------
有什么不对吗?
你的 while(!feof($fp1)) 只在读到文件尾的时候才成立
而最后一行的 fgets($fp1) 只是读完了内容,并没有读到文件尾
要到下一轮擦会读到文件尾

所以可写作
while($buf = fgets($fp1))<br />{   <br />    $read=explode(";", $buf);//字符串中用;来打成数组<br />    echo "read[0]= ".$read[0];// 用来测试<br />    echo "<br/>";<br />}

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