A method used by PHP feof to identify characters at the end of a file _php tips

Source: Internet
Author: User
EOF is a very important concept, and almost every major programming language provides the corresponding built-in function to verify that the parser has reached the file EOF. In PHP, this function is feof (). The feof () function is used to determine whether the end of the resource is reached. It is used frequently in file I/O operations. In the form of:
int feof (string resource)
Examples are as follows:
Copy Code code as follows:

<?php
$fh = fopen ("/home/www/data/users.txt", "RT");
while (!feof ($FH)) echo fgets ($FH);
Fclose ($FH);
?>

BOOL Feof (Resource $handle): Tests for End-of-file on a file pointer
This PHP manual the exact words above.
For convenience, I used to be like this before.
Copy Code code as follows:

<?php
If file can not be read or doesn ' t exist fopen function returns FALSE
$file = @fopen ("No_such_file", "R");
FALSE from fopen'll issue warning and result in Infinite loop
while (!feof ($file)) {
}
Fclose ($file);
?>

Sure, this is easier to use. However, if the above variable $file is not a valid file pointer or has been closed by fclose.
Then in the sixth line of the program, it will produce a waring, concurrent life and death cycle.
Why?
The reason is
Returns TRUE If the file pointer is in EOF or an error occurs (including socket timeout); otherwise returns FALSE.
Therefore, for the sake of safety, it is best to use the above code to add a judgment, Is_resource is still relatively safe.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.