Created
August 21, 2024 15:41
-
-
Save tranchausky/56b2a1e9211242d9fc48043169404dd2 to your computer and use it in GitHub Desktop.
file lớn, đọc ngược từ cuối file, đọc theo khối dữ liệu
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function getLastNonEmptyLine($file) { | |
$fp = fopen($file, 'r'); | |
$pos = -1; | |
$line = ''; | |
$block = ''; | |
if ($fp === false) { | |
return false; // Không thể mở file | |
} | |
// Đọc ngược từ cuối file theo khối 1024 byte | |
while ($pos > -filesize($file)) { | |
fseek($fp, $pos, SEEK_END); | |
$block = fread($fp, 1024); | |
$lines = explode("\n", $block); | |
// Kiểm tra từng dòng trong khối | |
foreach (array_reverse($lines) as $line) { | |
$line = trim($line); | |
if ($line !== '') { | |
fclose($fp); | |
return $line; // Trả về dòng cuối không rỗng | |
} | |
} | |
$pos -= 1024; | |
} | |
fclose($fp); | |
return false; // File không có dòng nào không rỗng | |
} | |
// Sử dụng hàm để lấy dòng cuối cùng không rỗng | |
$lastNonEmptyLine = getLastNonEmptyLine('yourfile.txt'); | |
echo $lastNonEmptyLine; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment