Board index   FAQ   Search  
Register  Login
Board index PHP PHP Scripts

Plz help me how this php script working

Links for php scripts

Moderators: macek, egami, gesf

Plz help me how this php script working

Postby anambd2010 » Sat Feb 18, 2012 10:29 pm

when counting lines the following code used:

$tr = fgets($fo, $file_length);
$total_rows = $total_rows + 1;


here $tr variable created where used can't understand. plz anybody help me?

the full scrip is given below:


<?php

$file = "data1.txt";
//-----Opening the file data1.dat.
//-----Is displayed.
$fo =@fopen($file, "r") or die("Could not locate the specified
file! Please check If the file is valid.");

//-----Calculating the total size of the file - test.txt.
$file_length = filesize($file);
echo "The total size of the file is: $file_length", "\n";

//---Reading the entire file row-wise. Each time a line ends,
//newline character is met, the variable
//---$total_rows Is Incremented by 1.
$total_rows=0;
while(!(feof($fo)))
{
$tr = fgets($fo, $file_length);
$total_rows = $total_rows + 1;
}
echo
echo "Total number of lines in this file is: $total_rows ",
"\n";
//---Closing data1.dat for the next loop to execute successfully.
fclose($fo);
?>
anambd2010
New php-forum User
New php-forum User
 
Posts: 1
Joined: Tue Feb 14, 2012 11:15 pm

Re: Plz help me how this php script working

Postby elephantecho » Tue Feb 28, 2012 9:57 pm

Hello,

It is ($tr) not used in script anywhere, but it is needed. As fgets reads single line from memory at a time. It means it will stop reading when new-line / EOF is reached.

Here while blocks keeps incrementing $total_rows until EOF is reached, hence $total_rows returns total lines in the file.

But the code returns (total lines +1) every time .
To fix this there is a change in order of $tr line and $total_rows++ line, incrementing should come before
$tr=fgets($fo,$file_length).

Right Way:
while(!(feof($fo)))
{
$total_rows = $total_rows + 1;
$tr = fgets($fo, $file_length);

}
User avatar
elephantecho
New php-forum User
New php-forum User
 
Posts: 2
Joined: Wed Mar 23, 2011 1:28 am
Location: Pune, India


Return to PHP Scripts

Who is online

Users browsing this forum: TurnitinBot [Bot] and 1 guest

Sponsored by Sitebuilder Web hosting and Traduzioni Italiano Rumeno and antispam for cPanel.