PHPEdit.net Community
   
1 2 3 4
Tutorials Tips Pasties Code Snippets
 

Home > Code snippets > PHP > Files > line_count

line_count

Created by LetsSurf, last update on 26/02/2008 17:32

trying to work out the line count on extremly large text file can't be done by simple str_count for line breaks as you can't load the entire file into memory. this function hopfully helps with that.

  1. $fp = fopen('php://temp', 'w+');
  2. $content = "Line1\nLine2\nLine3\n";
  3. fwrite($fp, $content);
  4.  
  5. echo line_count($fp);
  6.  
  7. function line_count($fp) {
  8. if (is_resource($fp) && (get_resource_type($fp) == 'file' ||
    get_resource_type($fp) == 'stream')) {
  9. $fpos = ftell($fp);
  10. rewind($fp);
  11. $bufferSize = 8192;
  12. $newLine = null;
  13. while(is_null($newLine) && !feof($fp)) {
  14. $buffer = fread($fp, $bufferSize);
  15. if (strpos($buffer, "\n") !== false) {
  16. $newLine = "\n";
  17. } else if(strpos($buffer, "\r") !== false) {
  18. $newLine = "\r";
  19. }
  20. }
  21. if (is_null($newLine)) {
  22. return 0;
  23. }
  24. $i = substr_count($buffer, $newLine);
  25. while (!feof($fp)) {
  26. $buffer = fread($fp, $bufferSize);
  27. $i += substr_count($buffer, $newLine);
  28. }
  29. fseek($fp, $fpos);
  30. return $i;
  31. } else {
  32. throw new Exception('invalid file handle as parameter');
  33. }
  34. }

Dependencies

No special requirements are needed by this snippet

By logging in you will be able to:

  • Recommand this page to someone else
  • Monitor changes on this item
  • Rate this item
  • Post comments
  • Download this item
Login now!

 
PHPEdit User Community, © 2008 WaterProof SARL
Powered by PHPEdit