search
HomeBackend DevelopmentPHP TutorialPHP中feof()函数实例测试_php技巧

本文实例讲述了PHP中的feof()函数的用法,针对feof()函数进行了一定的测试,很有实用价值。具体分析如下:

本文实例运行环境:

OS:Mac OS X 10.8.4
PHP:5.3.15

在PHP的官方手册中,函数feof()下面的讨论不少,对此做了一些相关的测试如下。

测试代码如下:

<&#63;php
print <<<EOF
<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>测试PHP中的feof()函数效果</title>
  </head>
  <body>
    <div>
EOF;
function bool2str($bool) {
  if ($bool == TRUE) {
    return "TRUE";
  } else {
    return "FALSE";
  }
}
/*
 * 请随便创建一个文件。
 * 比如:本测试中,在脚本文件的相同路径下创建了一个文本文件,
 * 文件内容为“abcdefg”,文件名为“7bytesfile”。
 */
$filename = './7bytesfile';
$handle = fopen($filename, 'r');
if (!$handle) {
  die("文件打开失败");
}
for($i = 0; $i <= filesize($filename); $i++) {
  fseek($handle, $i);
  echo "文件位置" . ftell($handle) . ":<br />\n";
  echo "执行fseek,尚未执行读取操作之前,feof结果:" . bool2str(feof($handle)) . "<br />\n";
  echo "当前位置字符:" . fgetc($handle) . "<br />\n";
  echo "执行文件读取操作之后,feof结果:" . bool2str(feof($handle)) . "<hr />\n";
}
/*
 * 通过上面一段代码可以观察到,
 * 随着循环的执行,文件指针从文件头一直移动到文件末尾。
 * 但是当完成了字符“g”的读取输出,文件指针继续向后移动,这是feof()依然返回False。
 * 只有当执行了一次fgetc()操作之后,才返回true,表示到达文件末尾。
 */
echo "ftell()结果:". ftell($handle). "<hr />\n";
//输出一下,很郁闷的发现文件指针的位置还是7。+_+

fseek($handle, 4);
echo "文件位置" . ftell($handle) . ":<br />\n";
echo "执行fseek,尚未执行读取操作之前,feof结果:" . bool2str(feof($handle)) . "<br />\n";
echo "当前位置字符:" . fgetc($handle) . "<br />\n";
echo "执行文件读取操作之后,feof结果:" . bool2str(feof($handle)) . "<hr />\n";

fseek($handle, 7);
echo "文件位置" . ftell($handle) . ":<br />\n";
echo "执行fseek,尚未执行读取操作之前,feof结果:" . bool2str(feof($handle)) . "<br />\n";
echo "当前位置字符:" . fgetc($handle) . "<br />\n";
echo "执行文件读取操作之后,feof结果:" . bool2str(feof($handle)) . "<hr />\n";
fclose($handle);
//再次移动文件指针,效果依旧。
//再用另外一段代码测试一下:

$handle = fopen($filename, 'r');
if (!$handle) {
  die("文件打开失败");
}
while (!feof($handle)) {
  $char = fgetc($handle);
  if ($char === FALSE) {
    echo 'FALSE';
  } else {
    echo $char;
  }
}
fclose($handle);
//依然是输出了字符g之后,再次执行读取操作,才终止循环。

print <<<EOF
    </div>
  </body>
</html>
EOF;
&#63;>

针对这种情况的猜测是,在PHP中,feof()的实现方式并非直接检查文件指针相对于文件的位置,而是根据某个标识返回结果。每次fseek()之后都会都会把这个标识设置为“False”,只有当执行一次文件内容读取操作之后,才会根据文件读取的结果对标识进行设置。

根据这种猜测,可以使用两种代码逻辑。

一个方法是不做feof()检测,直接检测内容读取函数(比如fgetc()、fgets())的执行结果。

示例代码如下:

while (($content = fgets($fileHandle)) !==FALSE) {
   //文件内容处理…… 
}

这种处理办法,利用了PHP被诟病的函数返回方式,所以得用“===”或“!==”进行检测,不能把代码简化成:

while ($content = fgets($fileHandle)) {}

另外一个方法是先进行一次文件读取,然后再进入feof()循环,如下所示:

$content = fgets($fileHandle);
while (!feof($fileHandle)) {
  //处理文件内容……
  $content = fgets($fileHandle); 
}

经过测试,前一种方法效率会高一些。

希望本文示例对大家PHP程序设计有所帮助。

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
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools