Jump to content

[SOLVED] Recursing thru files and directories


Xu Wei Jie

Recommended Posts

Hi

 

Recursive function will do it.

 

Basically have a function that loops through a directory (using readdir), with the directory name passed to it as a parameter. Call it once with the root directory. For each "file" found check if it is a directory and if it is then call the function again but passing the newly found directories full name. In the function you can also change values if you want.

 

Note that it will take a long time and potentially could cause a lot of damage if your editing went wrong.

 

All the best

 

Keith

I wrote this function but it seems to have a problem with the directory at the bottom. It recognizes that directory as a file. Any one can help out to see where I go wrong? Thanks

function TraverseDirectory($filedir,$change)
{
    if ($handle = opendir($filedir)) {
   
    /* This is the correct way to loop over the directory. */
    while (false !== ($file = readdir($handle))) {
        if( is_dir($file) )
	{
			$path = $filedir."/".$file;
			TraverseDirectory($path,$change);	
	}	
	else
	{
			$f = fopen($file,'r');
			$contents = fread($f, filesize($file));
			fclose($f);
	}	
        }
    }
    closedir($handle);
    return true;;
}

Hi

 

Cannot see anything obvious with it, but one potential error is that readdir will return both "." and "..". As such I think that you could potentially have an endless loop.

 

Try this to get rid of that possibility

 

function TraverseDirectory($filedir,$change)
{
if ($handle = opendir($filedir)) 
{
	/* This is the correct way to loop over the directory. */
	while (false !== ($file = readdir($handle))) 
	{
		if( is_dir($file) )
		{
			if ($file != '.' && $file !='..')
			{
				$path = $filedir."/".$file;
				TraverseDirectory($path,$change);
			}
		}	
		else
		{
			$f = fopen($file,'r');
			$contents = fread($f, filesize($file));
			fclose($f);
		}	
	}
}
closedir($handle);
return true;;
}

 

All the best

 

Keith

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.