How can I retrieve the last data of a file in reverse order without reading all the file content? how can I retrieve the last data of a file in reverse order without reading all the file content? Demo: Filename: menu.txt Content: aaaaaaaabbbbbbbbccccccccddddddeeeeeeeeeeresult :( retrieve the last 3 Records) how to retrieve the last few pieces of data in reverse order without reading all the file Content
How can I retrieve the last few pieces of data in reverse order without reading all the file content?
Demo:
Filename: menu.txt
Content:
Aaaaaaaa
Bbbbbbbb
Cccccccc
Dddddddd
Eeeeeeee
Result: (retrieve the last 3 Records)
$ Res = array (
Array ("eeeeeeee "),
Array ("dddddddd "),
Array ("cccccccc "),
);
------ Best solution --------------------
$ Filename = "menu.txt"; // file name
$ Handle = fopen ($ filename, "rb ");
If (fseek ($ handle, 0, SEEK_END )! =-1) {// point to the end of the file
$ K = 3; // The number of retrieved entries
$ S = 0;
While ($ k --){
If (fseek ($ handle, $ S-1, SEEK_END) ===-1) break; // move the pointer forward to a position
While (fgetc ($ handle )! = "\ N "){
-- $ S;
Fseek ($ handle, $ s, SEEK_END );
}
Fseek ($ handle, $ s + 1, SEEK_END); // move the pointer to a position
Echo fgets ($ handle )."
";
}
} Else {
Echo 'no ';
}
You can see
------ Other solutions --------------------
This post was last edited by xuzuning at 12:46:50, January 21 ,.
$ N = 3; // Get 3 rows
$ Fp = fopen('menu.txt ', 'r'); // open the file
Fseek ($ fp,-1, SEEK_END); // jump to the last byte
$ Res = array (); // Initialization result array
$ T = ''; // initialize the buffer
While ($ n & $ ch = fgetc ($ fp) {// read cyclically
Switch ($ ch ){
Case "\ n ":
Case "\ r": // It is the end of a row
If ($ t ){
Array_unshift ($ res, $ t); // Save the buffer
$ N --;
}
$ T = '';
Break;
Default:
$ T = $ ch. $ t; // cache characters
}
Fseek ($ fp,-2, SEEK_CUR); // jump forward to 2 characters
}
Print_r ($ res );
Array
(
[0] => cccccccc
[1] => dddddddd
[2] => eeeeeeee
)
------ Other solutions --------------------
"\ R": // It is the end of a row.
# Echo "--> 4
";
If ($ t) {# is $ n true?
Array_unshift ($ res, $ t); // Save the buffer
Echo "res -->"; print_r ($ res); echo"
";
$ N --;
}
$ T = '';
Break;
Default:
# Echo "--> 5
";
$ T = $ ch. $ t; // cache character # What is the relationship between $ t and the final result?
}
Fseek ($ fp,-2, SEEK_CUR); // jump forward to 2 characters
}
Return $ res;
}
------ Other solutions --------------------
If you read the data, you can read the data by row.
------ Other solutions --------------------
Move the file pointer to the location where you want to start reading (using the fseek () function) and then read the file.
------ Other solutions --------------------