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

Link to comment
Share on other sites

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;;
}

Link to comment
Share on other sites

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.