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
310 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 125 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

Best Practices: Disaster Recovery Testing

Besides backup, any IT division should have a disaster recovery plan. You will find a few tips below relating to the development of such a plan and to what issues one should pay special attention in the course of backup planning.

Question has a verified solution.

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

Popularity Can Be Measured Sometimes we deal with questions of popularity, and we need a way to collect opinions from our clients.  This article shows a simple teaching example of how we might elect a favorite color by letting our clients vote for …
Foreword (July, 2015) Since I first wrote this article, years ago, a great many more people have begun using the internet.  They are coming online from every part of the globe, learning, reading, shopping and spending money at an ever-increasing ra…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
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 …

831 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