Forum Moderators: coopster
Main File
--Monthly totals
----January Data Files
------01.dat
------02.dat
------etc. etc.
----February Data Files
------01.dat
------02.dat
------etc. etc.
--Totals
----01.txt
----02.txt
----etc. etc.
I have a script that opens each dat file, reads the number (each file has just one number that can be several digits of course), and then adds it to the number in the corresponding txt file under totals. With me so far?
Now, if I break out my handy dandy calculator, and open each 01.dat from each months folder and add them together, I get a completely different answer.
I have also, cleared the totals txt files and ran it from th begining several times and get different answers each time as well.
here is the basic breakdown of my code:
if(is_dir($sDir)){
$file = scandir($sDir);
foreach($file as $name) {
$tmp = explode(".", $name);
$hand = $tmp[0];
$userDat = $sDir.$hand.".dat";if($userDat == $sDir.".dat") { continue; } else {
$op = fopen($userDat, "r");
$num = fread($op, filesize($userDat));
fclose($op);
$totFile = "users/".$hand.".dat";
if(file_exists($totFile)) {
$op = fopen($totFile, "r");
$pNum = fread($op, filesize($totFile));
fclose($op);
$nNum = $num+$pNum;$op = fopen($totFile, "w+");
fwrite($op, $nNum);
fclose($op);
}else{
$op = fopen($totFile, "w+");
fwrite($op, $num);
fclose($op);
}
}
}
Granted, it might not be the best way to do it, but it works with the exception of the total not being correct. Well, seeing as that is what I am after (the total), I guess this doesnt work. LOL.
Could this possibly be caused by the use of a slower PC to run the script? As there are several years and several hundred files to tally, it takes 10-15 minutes to complete.
Any help is appreciated.
IamStang
Do you have only one value in each file? Moreover you had logic mistake. I would change the code to this:
$total = 0;//setup
if(is_dir($sDir)){//check dir
$file = scandir($sDir);
foreach($file as $name) {
$tmp = explode(".", $name);
if(($ext = $tmp[1])!= "dat") {echo "$name is not a dat file"; continue;} //check if dat
$userDat = $sDir.$tmp[0].".dat";if(!($op = fopen($userDat, "r")) {echo "Cannot open file $userDat"; continue;} // check if can open the file
$num = fread($op, filesize($userDat));
fclose($op);
$total += $num;
}//end foreach
$totFile = $sDir."/total.txt";
$op = fopen($totFile, "w");
fwrite($op, $total);
fclose($op);
}//end if dir