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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

I imagine that there are some, like me, who require a way of getting currency exchange rates for implementation in web project from time to time, so I thought I would share a solution that I have developed for this purpose. It turns out that Yaho…
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.
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

911 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

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now