[英]Determine if a file has more than X lines?
因為我無法找到一個檢索文件行數的函數,所以我需要使用它
$handle = fopen("file.txt");
For($Line=1; $Line<=10; $Line=$Line+1){
fgets($handle);
}
If feof($handle){
echo "File has 10 lines or more.";
}Else{
echo "File has less than 10 lines.";
}
fclose($handle)
或類似的東西? 我想知道的是文件是否超過10行:-)。
提前致謝!
您可以使用以下方式獲取行數:
$file = 'smth.txt';
$num_lines = count(file($file));
更快,更多的內存資源:
$file = new SplFileObject('file.txt');
$file->seek(9);
if ($file->eof()) {
echo 'File has less than 10 lines.';
} else {
echo 'File has 10 lines or more.';
}
如果你有一個LARGE文件會出現這個更大的問題,PHP往往會減慢一些。 為什么不運行exec命令讓系統返回號碼? 然后,您不必擔心讀取文件的PHP開銷。
$count = exec("wc -l /path/to/file");
或者,如果你想要更多的幻想:
$count = exec("awk '// {++x} END {print x}' /path/to/file");
如果您有大文件,那么最好是分段讀取文件並計算“\\ n”字符,或者什么是lineend字符,例如在某些系統上,您還需要“\\ r”計數器或其他...
$lineCounter=0;
$myFile =fopen('/pathto/file.whatever','r');
while ($stringSegment = fread($myFile, 4096000)) {
$lineCounter += substr_count($stringSegment, "\n");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.