admin 发表于 2023-2-16 18:54:47

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