简体   繁体   中英

Determine if a file has more than X lines?

as I was not able to find a function which retrieves the amount of lines a file has, do I need to use

$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)

or something similar? All I want to know is if the file has more than 10 lines or not :-).

Thanks in advance!

You can get the number of lines using:

$file = 'smth.txt';    
$num_lines = count(file($file));

Faster, more memory resourceful:

$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.';
}

SplFileObject

This bigger problems will occur if you have a LARGE file, PHP tends to slow down some. Why not run an exec command and let the system return the number? Then you do not have to worry about the PHP overhead to read the file.

$count = exec("wc -l /path/to/file");

Or if you want to get a bit more fancy:

$count = exec("awk '// {++x} END {print x}' /path/to/file");

If you have big file then better schould be read files in segments and counts "\\n" chars, or what ever is the lineend char, for example on some systems you will also need "\\r" counter or whatever...

$lineCounter=0;
$myFile =fopen('/pathto/file.whatever','r');
   while ($stringSegment = fread($myFile, 4096000)) {
$lineCounter += substr_count($stringSegment, "\n");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM