PHP 文件处理
<div id="article_content" class="article_content clearfix"><link rel="stylesheet" href="https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/kdoc_html_views-1a98987dfd.css">
<link rel="stylesheet" href="https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/ck_htmledit_views-6e43165c0a.css">
<div id="content_views" class="htmledit_views">
<p>fopen() 函数用于在 PHP 中打开文件。</p>
<hr>
<h2>打开文件</h2>
<p>fopen() 函数用于在 PHP 中打开文件。</p>
<p>此函数的第一个参数含有要打开的文件的名称,第二个参数规定了使用哪种模式来打开文件:</p>
<p><html><br> <body><br><br> <?php<br> $file=fopen("welcome.txt","r");<br> ?><br><br> </body><br> </html></p>
<p>文件可能通过下列模式来打开:</p>
<table><tbody><tr><th>模式</th><th>描述</th></tr><tr><td>r</td><td>只读。在文件的开头开始。</td></tr><tr><td>r+</td><td>读/写。在文件的开头开始。</td></tr><tr><td>w</td><td>只写。打开并清空文件的内容;如果文件不存在,则创建新文件。</td></tr><tr><td>w+</td><td>读/写。打开并清空文件的内容;如果文件不存在,则创建新文件。</td></tr><tr><td>a</td><td>追加。打开并向文件末尾进行写操作,如果文件不存在,则创建新文件。</td></tr><tr><td>a+</td><td>读/追加。通过向文件末尾写内容,来保持文件内容。</td></tr><tr><td>x</td><td>只写。创建新文件。如果文件已存在,则返回 FALSE 和一个错误。</td></tr><tr><td>x+</td><td>读/写。创建新文件。如果文件已存在,则返回 FALSE 和一个错误。</td></tr></tbody></table>
<p><strong>注释:</strong>如果 fopen() 函数无法打开指定文件,则返回 0 (false)。</p>
<h3>实例</h3>
<p>如果 fopen() 函数不能打开指定的文件,下面的实例会生成一段消息:</p>
<p><html><br> <body><br><br> <?php<br> $file=fopen("welcome.txt","r") or exit("Unable to open file!");<br> ?><br><br> </body><br> </html></p>
<p></p>
<hr>
<h2>关闭文件</h2>
<p>fclose() 函数用于关闭打开的文件:</p>
<p><?php<br> $file = fopen("test.txt","r");<br><br> //执行一些代码<br><br> fclose($file);<br> ?></p>
<p></p>
<hr>
<h2>检测文件末尾(EOF)</h2>
<p>feof() 函数检测是否已到达文件末尾(EOF)。</p>
<p>在循环遍历未知长度的数据时,feof() 函数很有用。</p>
<p><strong>注释:</strong>在 w 、a 和 x 模式下,您无法读取打开的文件!</p>
<p>if (feof($file)) echo "文件结尾";</p>
<p></p>
<hr>
<h2>逐行读取文件</h2>
<p>fgets() 函数用于从文件中逐行读取文件。</p>
<p><strong>注释:</strong>在调用该函数之后,文件指针会移动到下一行。</p>
<h3>实例</h3>
<p>下面的实例逐行读取文件,直到文件末尾为止:</p>
<p><?php<br> $file = fopen("welcome.txt", "r") or exit("无法打开文件!");<br> // 读取文件每一行,直到文件结尾<br> while(!feof($file))<br> {<br> echo fgets($file). "<br>";<br> }<br> fclose($file);<br> ?></p>
<p></p>
<hr>
<h2>逐字符读取文件</h2>
<p>fgetc() 函数用于从文件中逐字符地读取文件。</p>
<p><strong>注释:</strong>在调用该函数之后,文件指针会移动到下一个字符。</p>
<h3>实例</h3>
<p>下面的实例逐字符地读取文件,直到文件末尾为止:</p>
<p><?php<br> $file=fopen("welcome.txt","r") or exit("无法打开文件!");<br> while (!feof($file))<br> {<br> echo fgetc($file);<br> }<br> fclose($file);<br> ?></p>
</div>
</div>
<div id="treeSkill"></div>
页:
[1]