Sunday, August 2, 2015

Efficiently counting the number of lines of a text file. (200mb+)


I have just found out that my script gives me a fatal error:
Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 440 bytes) in C:\process_txt.php on line 109
That line is this:
$lines = count(file($path)) - 1;
So I think it is having difficulty loading the file into memeory and counting the number of lines, is there a more efficient way I can do this without having memory issues?
The text files that I need to count the number of lines for range from 2MB to 500MB. Maybe a Gig sometimes.
Thanks all for any help.
shareimprove this question

11 Answers

up vote79down voteaccepted
This will use less memory, since it doesn't load the whole file into memory:
$file="largefile.txt";
$linecount = 0;
$handle = fopen($file, "r");
while(!feof($handle)){
  $line = fgets($handle);
  $linecount++;
}

fclose($handle);

echo $linecount;
fgets loads a single line into memory (if the second argument $length is omitted it will keep reading from the stream until it reaches the end of the line, which is what we want). This is still unlikely to be as quick as using something other than PHP, if you care about wall time as well as memory usage.
The only danger with this is if any lines are particularly long (what if you encounter a 2GB file without line breaks?). In which case you're better off doing slurping it in in chunks, and counting end-of-line characters:
$file="largefile.txt";
$linecount = 0;
$handle = fopen($file, "r");
while(!feof($handle)){
  $line = fgets($handle, 4096);
  $linecount = $linecount + substr_count($line, PHP_EOL);
}

fclose($handle);

echo $linecount;
shareimprove this answer
   
Thanks for the explanation Dominic - that looks good. I had a feeling it had to be done line by line and not letting count of file load the whole thing into memory! –  Abs Jan 29 '10 at 14:38
   
The only danger of this snippet are huge files without linebreaks as fgets will then try to suck up the whole file. It'd be safer to read 4kB chunks at a time and count line termination characters. –  David Schmitt Jan 29 '10 at 14:51
   
@David - how does my edit look? I'm not 100% confident about PHP_EOL - does that look right? – Dominic Rodger Jan 29 '10 at 14:58
2 
not perfect: you could have a unix-style file (\n) being parsed on a windows machine (PHP_EOL == '\r\n') –  nickf Jan 29 '10 at 15:01
   
@nickf - good point. How would you address it? How does fgets work? –  Dominic Rodger Jan 29 '10 at 15:23

http://stackoverflow.com/questions/2162497/efficiently-counting-the-number-of-lines-of-a-text-file-200mb

Counting Lines in php

Counting Lines in php

How to count the number of lines in a file using php?

Explanation

To explain it we assume a file named test.txt with two lines in it.
Step 1:
Define the file name in to a variable
Example: $file1 = "./test.txt";
Step 2:
Create a instance for the file using the method file('filename')
Example: $lines = file($file1);
Here we create a file instance for the file by passing the variable $file1 created in step 1. The result is stored in the variable $lines, which will be an array of lines.
Step 3:
Now we can count the lines by passing the array of lines ($lines) to the method count()
Example: $count = count($lines);
The method "count()" takes an array as argument and returns the number of lines in it.
Step 4:
Printing the result using the function echo('string');
Example: echo($count)

So totally the code is
<?php
$file1 = "./test.txt";
$lines = file($file1);
$count = count($lines);
echo($count);
?>
Result: 2
https://www.hscripts.com/tutorials/php/file-functions/count-lines.php

Using fopen() to write file into subdirectory


I already looked at this StackOverflow question and it didn't help (similarly titled).
I'm passing an image in from my Android application. If I type
$file = fopen('test.jpg', 'wb');
It works correctly and the image uploads; however, I want to allow for multiple uploads from android phones, so I want to randomize the name of the .jpg file so that I can save each new upload as a different name. I was trying this below:
$destination =  time() + rand(1, 1000) . ".jpg";
$url_destination = "/project_images/" . $destination;

$file = fopen($url_destination, 'wb');
fwrite($file, $binary);
fclose($file);
It doesn't write the file to the server, however. I tried different variations of the URL there - with 'project_images/', '/project_images/', even trying the full URL (which the aforementioned StackOverflow post corrected me on), and I still can't get it to write.
The permissions of the project_images folder are set to allow files to be written to it. Any ideas?
shareimprove this question
1 
fopen cannot write to a URL, so $url_destination is definitely starting on the wrong foot. The path must be a local filesystem path. –  Jon Dec 7 '12 at 10:06 
   
try to change permissions to 777 for /project_images directory –  Nick Dec 7 '12 at 10:10
   
   
@ÁlvaroG.Vicario The OP already stated in his question that that question doesn't fix his problem. – JaredMcAteer Dec 7 '12 at 14:19
   
@JaredMcAteer - The OP admitted later that "he didn't upload properly". –  Álvaro G. Vicario Dec 7 '12 at 15:54
Your problem is "/project_images" which is a wrong absolute path.
For it to work change it to "project_images/" or dirname(__FILE__).'/project_images/'.
shareimprove this answer
   
I thought I had tried that one already (see my post where I actually included that!), but I guess it didn't upload properly. This solved it. –  Isaac Askew Dec 7 '12 at 10:09
1 
Great :) .. usually using dirname(FILE) is the best solution in these cases –  Sorin Trimbitas Dec 7 '12 at 10:10
1 
+1 i <3 dirname(FILE) –  Dale Dec 7 '12 at 10:11
   
Another improvement of your code .. try to stick to ' instead of " if you don't use code like this : $str = "content of test is $test"; –  Sorin Trimbitas Dec 7 '12 at 10:13

php - file append

So far we have learned how to open, close, read, and write to a file. However, the ways in which we have written to a file so far have caused the data that was stored in the file to be deleted. If you want to append to a file, that is, add on to the existing data, then you need to open the file in append mode.

php - file open: append

If we want to add on to a file we need to open it up in append mode. The code below does just that.

PHP Code:

$myFile = "testFile.txt";
$fh = fopen($myFile, 'a');
If we were to write to the file it would begin writing data at the end of the file.

php - file write: appending data

Using the testFile.txt file we created in the File Write lesson , we are going to append on some more data.

PHP Code:

$myFile = "testFile.txt";
$fh = fopen($myFile, 'a') or die("can't open file");
$stringData = "New Stuff 1\n";
fwrite($fh, $stringData);
$stringData = "New Stuff 2\n";
fwrite($fh, $stringData);
fclose($fh);
You should noticed that the way we write data to the file is exactly the same as in the Write lesson. The only thing that is different is that the file pointer is placed at the end of the file in append mode, so all data is added to the end of the file.
The contents of the file testFile.txt would now look like this:

Contents of the testFile.txt File:

Floppy Jalopy
Pointy Pinto
New Stuff 1
New Stuff 2

php - append: why use it?

The above example may not seem very useful, but appending data onto a file is actually used everyday. Almost all web servers have a log of some sort. These various logs keep track of all kinds of information, such as: errors, visitors, and even files that are installed on the machine.
A log is basically used to document events that occur over a period of time, rather than all at once. Logs: a perfect use for append!