This article describes the PHP implementation of similar to the C language file reading and parsing capabilities. Share to everyone for your reference, as follows:
$log _file_name = ' d:/static/develop/kuai_zhi/acagrid.com/public/logs/'. Date (' Ym '). ' /'. Date (' d '). ' _error.log ';//$log _file_name = ' D:/static/develop/kuai_zhi/acagrid.com/public/logs/201701/19_error.log '; if (!file _exists ($log _file_name)) return, $handle = fopen ($log _file_name, ' RB '); if (FALSE = = = $handle) { exit ("Failed to open stream to URL");} $stream = fread ($handle, $length);//From the current pointer position of the file, read n bytes length//reset the position of the file pointer. Specifies the position of the pointer after the pointer position has been modified. Read the file, the following is from this position to read the//fseek ($handle, a);//fgets represents one line per read of a file $error_log_array = [];while ($line = fgets ($handle))!== False) { //each read line ///match appears in the 1],TP log with this fatal error type if (Preg_match ("/\[1\]/", $line)) { $error _log_array[ ] = $line; }} Fclose ($handle);
A few points to note:
1. If you are using fwrite, be careful to avoid emptying the contents of the original file. The key is the way fopen is opened. R or W.
If the Append method is used, the a tag.
2, fopen, pay attention to determine whether to open the file successfully. Avoid using feof to enter the dead loop. Because of this function, when passed in is not a pointer, this function will always return false
Feof's intention is to determine whether the end of the file. Returns true if it is the end. Not end returns false. If an illegal pointer is passed in, it is never the end of the file and always returns false.
The feof () function, when passed in is not a pointer type, use the following to determine a dead loop
while (!feof ($FP)) {}
3, Fread and fgets. Reads the file one line at a line, then uses Fgets. is not read by line, it is read with Fread ().
Note This detail: if there is no more content, it returns false, that is, two cases, if the contents are empty. also returns false. When reading to the end of the file, these two functions also return False (no wonder we use feof () so that we do not find this detail, because this function has helped us to determine the end of the file)
4, use the Append method (that is, a mark) to open the file, to note that in this way, can not read the contents of the file, only to write to the file. So Fread () for this handle will get false.
The summary is, if just read the contents of the file, only read the way open, if it is to write new content in, then use a to open the way
The
Now understands why different patterns are differentiated. I used to think it was useless. Now it seems that the way you open the file determines what you can do with the file (add new content or read the content). )