2

因为我找不到一个函数来检索文件的行数,我需要使用吗

$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 行:-)。

提前致谢!

4

4 回答 4

5

您可以使用以下方法获取行数:

$file = 'smth.txt';    
$num_lines = count(file($file));
于 2010-08-18T19:14:36.490 回答
2

更快,更多的内存资源:

$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

于 2010-08-18T19:36:35.097 回答
2

如果你有一个大文件,就会出现这个更大的问题,PHP 往往会减慢一些速度。为什么不运行 exec 命令并让系统返回数字?然后您不必担心读取文件的 PHP 开销。

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

或者,如果您想更花哨:

$count = exec("awk '// {++x} END {print x}' /path/to/file");
于 2010-08-18T19:39:47.567 回答
0

如果您有大文件,那么最好分段读取文件并计算“\n”字符,或者lineend char,例如在某些系统上,您还需要“\r”计数器或其他什么...

$lineCounter=0;
$myFile =fopen('/pathto/file.whatever','r');
   while ($stringSegment = fread($myFile, 4096000)) {
$lineCounter += substr_count($stringSegment, "\n");
}
于 2010-08-18T20:05:23.643 回答