|
Matt McBride - 2005-06-06 17:44:20
This function is actually incorrect. Let's say you have a file with 9500 lines and you want to split the file by 1000 lines. The currect code will make 9 files with 1000 lines per file... well what about the other 500 lines. There should be a tenth file with the remaining lines.
Here is the corrected run function:
function run(){
$i=0;
$j=1;
$date = date("m-d-y");
unset($buffer);
$lines = file($this->Getsource());
$num_lines = count($lines);
unset($lines);
$num_of_files = ceil($num_lines / $this->_lines);
echo $num_of_files;
$handle = @fopen ($this->Getsource(), "r");
$buffer = '';
$i = '';
while (!feof ($handle)) {
$buffer .= @fgets($handle, 4096);
$i++;
if ($i >= $this->_lines) {
$fname = $this->Getpath().$date.$j.".txt";
if (!$fhandle = @fopen($fname, 'w')) {
print "Cannot open file ($fname)";
exit;
}
if (!@fwrite($fhandle, $buffer)) {
print "Cannot write to file ($fname)";
exit;
}
fclose($fhandle);
unset($buffer,$i);
$j++;
} else if ($j == $num_of_files) {
$fname = $this->Getpath()."products".$j.".txt";
if (!$fhandle = @fopen($fname, 'w')) {
print "Cannot open file ($fname)";
exit;
}
if (!@fwrite($fhandle, $buffer)) {
print "Cannot write to file ($fname)";
exit;
}
fclose($fhandle);
unset($buffer,$i);
}
}
fclose ($handle);
}
Matt McBride - 2005-06-06 18:37:34 - In reply to message 1 from Matt McBride
Actually, here is the corrected and tested change to that function...
function run(){
$i=0;
$j=1;
$date = date("m-d-y");
unset($buffer);
$lines = file($this->Getsource());
$num_lines = count($lines);
unset($lines);
$num_of_files = ceil($num_lines / $this->_lines);
$remainder = $num_lines % $this->_lines;
$handle = @fopen ($this->Getsource(), "r");
$buffer = '';
$i = '';
while (!feof ($handle)) {
$buffer .= @fgets($handle, 4096);
$i++;
if ($i >= $this->_lines) {
$fname = $this->Getpath().$date.$j.".txt";
if (!$fhandle = @fopen($fname, 'w')) {
print "Cannot open file ($fname)";
exit;
}
if (!@fwrite($fhandle, $buffer)) {
print "Cannot write to file ($fname)";
exit;
}
fclose($fhandle);
unset($buffer,$i);
$j++;
} else if (($j == $num_of_files) AND ($i >= $remainder)) {
$fname = $this->Getpath().$date.$j.".txt";
if (!$fhandle = @fopen($fname, 'w')) {
print "Cannot open file ($fname)";
exit;
}
if (!@fwrite($fhandle, $buffer)) {
print "Cannot write to file ($fname)";
exit;
}
fclose($fhandle);
unset($buffer,$i);
$j++;
}
}
fclose ($handle);
}
Ben Yacoub Hatem - 2005-06-07 08:01:24 - In reply to message 2 from Matt McBride
Sorry I was off for long time. Thank you for your contribution, but you see there is no need to open the file twice using file() then fopen() ... just to count the missing lines. This information exist already in the variable $buffer. I have update the class so just check it again.
|