Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Code to demonstrate an efficient way to search the last 100 lines of a file containing roughly ten million lines for a sample string. This should function without having to process each line of the fi

Posted on 2009-03-31
2
Medium Priority
?
339 Views
Last Modified: 2013-12-12
Code to demonstrate an efficient way to search the last 100 lines of a file containing roughly ten million lines for a sample string. This should function without having to process each line of the file (and without making use of the tail command or any external system commands). Any of the following languages can be used
0
Comment
Question by:pradipinfo
2 Comments
 
LVL 5

Accepted Solution

by:
Pantalaim0n earned 500 total points
ID: 24038607
How about this? It only needs a rough indication of the maximum length of a string in the file and the number of strings you want to return.
<?php
	$filename        = ".\\longfile.txt";
	$filesize        = filesize($filename);
	$max_line_length = 1024;
	$num_lines       = 100;
	$file = fopen($filename,"r");
	fseek($file,$filesize-($max_line_length*$num_lines));
	$arr = array();
	for ($i=0;$i<$num_lines;$i++) $arr[] = "";
	while (!feof($file)) {
		$line = fgets($file);
		array_splice($arr,0,1);
		$arr[] = $line;
	}
	
	$linenr = 1;
	foreach ($arr as $line) { echo "(".$linenr.") - ".$line."<br />"; $linenr++; }
?>

Open in new window

0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
There are times when I have encountered the need to decompress a response from a PHP request. This is how it's done, but you must have control of the request and you can set the Accept-Encoding header.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …
Suggested Courses

916 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question