Sign in to follow this  
AzeoTech

Recursive functions

Recommended Posts

A common, and quite useful programming technique is the recursive function. This is when a function calls itself with different parameters to work through some sort of complex structure. The best example for this is the population of a tree control with the directory structure of a harddrive. A function can be created to fill in a particular directory, and then that function can call itself for each of the subdirectories, working its way through the entire drive using only a few lines of code. This could be useful if you have a subdirectory tree for storing logged files and you want your users to be able to select files from the tree without using the File.FileOpenDialog() function which allows them access to the root and other areas of the harddrive.

I've attached an example of doing exactly this using DAQFactory (requires 5.79+). Click on the PopulateTree button to start the process. The number Number Files/Directories will increase as its doing it. You can stop the process by clicking the same button. You can then double click on any file in the tree and full path and file size is displayed (see the tree list's properties for the script for this).

The recursion starts with the PopulateTree sequence which clears out the tree, determines and adds the root, then calls RecurseDirectory() on it. RecurseDirectory is the one that repetitively calls itself as it works down the directory tree. I've added some optimization (see comments in script), but without it, the whole RecurseDirectory function could be about 10 lines.

One key point about recursion is making sure you there is an end. In this case, doing GetFilePathList() will return the . and .. paths which in Windows signify the current and parent directory. If we recurse on these, we'll end up in a infinite recursive loop. These are VERY BAD and result in a blown stack. A blown stack is something that DAQFactory cannot recover from and DAQFactory will just quit with no warning. Which brings up another important point:

When working with recursive loops, I strongly recommend walking through the code using the debugger, at least the first time. I made the mistake of not doing this and had forgotten about the . and .. issue and so blew the stack and crashed DAQFactory. Once I walked through it, looking at the variables I knew exactly what had caused it.

Recursive loops work well whenever there is some sort of tree like structure and make for very clean code. Feel free to post if you have questions about the sample or recursion in general.

treelistdirectory.ctl

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this