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
314 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

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Wordpress Pagination Function Not working ? 7 39
Fulfillment API php code sample 1 58
Wordpress French and English Site 6 77
Ajax and PHP 9 29
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 …
This article will explain how to display the first page of your Microsoft Word documents (e.g. .doc, .docx, etc...) as images in a web page programatically. I have scoured the web on a way to do this unsuccessfully. The goal is to produce something …
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

856 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