TweetFollow Us on Twitter

Vol Search XFCN
Volume Number:7
Issue Number:6
Column Tag:HyperChat

Related Info: File Manager

HFS Volume Search XFCN

By Mark Armstrong, Pharos Technologies

Note: Source code files accompanying article are located on MacTech CD-ROM or source code disks.

The SearchVol XFCN

The SearchVol XFCN searches the specified volume and returns the full path name of the file. This is extremely useful if you want to launch a document from within Hypercard but you are not sure where the file is located on the volume. SearchVol will return the full pathname of the file which you can then pass directly to the Hypertalk open command.

SearchVol uses a recursive algorithm to walk through the hierarchical file structure looking for a match. If it finds a match, it constructs the full path name by walking back up the tree. Once it has the full path name, it returns it to Hypercard. If no match is found, the XFCN will return empty. See the Other Issues section of this article for further discussion of the recursive nature of the algorithm.

SearchVol searches in the specified volume, or, if no volume is specified, in the system volume. Since PBGetVInfo prefers to have the volume specified in the form “volname:” (and since I am in the unfortunate habit of just passing “volume” without the trailing colon,) we simply check to see if there is a trailing colon on the specified volume name. If there is not, we add one.

Once we have the volume reference numbers we can begin the search. We start by determining the number of files and directories in the root directory by calling PBGetCatInfo and then we make the initial call to SearchFile, which is the real guts of the XFCN.

The Search Engine

The SearchFile function is very similar to Clifford Story’s walktree function in the October ’88 MacTutor (Programmer’s Workshop; HFS Transfer DA) Cliff wrote his in Pascal - this one is in C. But the structure of the routines is quite similar. For the gospel on searching HFS volumes, refer to Apple’s Technical Note 68.

You will notice that SearchFile consists of two for loops. The first for loop is looking for files. We look for file by accepting only the cases in which bit 4 of ioFlAttrib is not set. The second for loop is looking strictly for directories. If it is a file, then we check to see if there is a match. If it is a directory, then we look inside that directory with a recursive call to search file.

So, why the two for loops? Well, I wanted the routine to be equivalently fast for any file in a given directory. With just a single for loop, a file in the route directory named “AAAA” would most likely be found very quickly. Where as, a file named “ZZZZ” would take much longer, assuming, of course, that the volume in question was an average user’s 40 meg hard disk. Consequently, if we look through all the files first for a given directory before diving down to the next level in the hierarchy, we should be able to get a more consistent search time for files at the same hierarchical level. Once the recursive searching is complete, we check to see if a file was found. If a file was not found, fErr will contain fnfErr. On the other hand, if a file was found then we need to walk back up the hierarchy to construct the full path name that Hypercard requires for its file commands such as open, read, and print. We build the path name in the returnValue handle so it is available when we return to Hypercard.

Error Handling

In the SearchVol XFCN listed below I have included only a skeletal version of the required error handling. I have done this so as not to cloud the concepts on which I am trying to focus. However, I do have a few words about error handling that I would like to share.

There is an interesting catch-22 situation that arises for the author of external functions. The situation is this. If Hypercard is expecting you to return a value from an external function, then Hypercard needs a way to determine if the returned value is an error string or the expected result. In many XFCN’s available today, it is difficult (if not impossible) to determine in the general case if the string returned from the external is an error or not. As an example, suppose there is an XFCN that returns a file name. Furthermore, lets say that in case of error, the XFCN returns the error number. Now lets say that the XFCn is called from Hypertalk and the returned result is “-43”. Is this an error code for file not found or is it just a file that happens to be named “-43”. To avoid these problematic circumstances, the XFCN designer must make it very easy for the Hypertalk programmer to ascertain:

1) If an error occurred

2) What was the nature of the error

Another common approach is to return empty if an error occurred. Unfortunately, empty does not tell the Hypertalk programmer (to say nothing of the user) what went wrong. Consequently, it is difficult to take appropriate action.

Some programmers have circumnavigated the problem by forcing the declaration of a global variable. If an error occurs, then the global variable is set to notify Hypertalk that things did not go as planned. This method works has its advantages, but it can be an extra hassle if the Hypertalk programmer does not know he is required to declare the global. Whatever you decide to do, make your error checking rigorous and complete. Everyone will benefit.

Other Issues

SearchVol, as it is, is a foundation on which one can build. For example, one could easily search all mounted volumes by creating an outside loop that walked through the volume queue. For example:

/* 1 */

QHdrPtr QQ;
VCB     *Cur;

QQ = GetVCBQHdr();
Cur = (VCB *)(QQ->qHead);
   
do {
   /* Use Cur->vcbVN as the current volName */
   /* Put search volume code here */
   Cur = (VCB *)(Cur)->qLink;
   } while (Cur != 0L);

Another possibility is to extend the XFCN so that it returns all occurrences of the specified file - rather than just the first occurrence. In such a case, you would not return after finding a file but would simply store the full pathname of the file and then continue the search down the hierarchy. In this way, you could duplicate in Hypercard the functionality of the Find File desk accessory.

Other ideas include filtering out files by type or modification date, cataloging subdirectories on a volume, and the list goes on.

Finally, it is important to discuss the advantages and limitations of using a recursive algorithm for hierarchical searching. The advantages are that the code is small and simple. The primary limitation is that the stack grows with each recursive call. On a large hard disk or CD-ROM this could be a problem. I have used the recursive algorithm as a demonstration of recursive methods in an ideal world. Reality dictates that machines have a finite amount of memory. It is more prudent to employ methods which are not recursive if there is any possibility of exceeding available stack space.

/*------------------------------------------------
 SearchVol XFCN
 © 1989 MacTutor
 by Mark Armstrong    Pharos Technologies, Inc
 written in Think’s LightspeedC 3.0
------------------------------------------------*/

#include “HyperXCmd.h”
#include “FileMgr.h”
#include “HFS.h”
#include “ResourceMgr.h”
#include “SetUpA4.h”

#define False    0
#define True!False
#define Nil 0L

/*--------------------------------------
XFCN main function
--------------------------------------*/
pascal main(paramPtr)
   XCmdBlockPtr  paramPtr;
   {
   Str255 fName,str,fullPath,vName;
   HParamBlockRecMyHPB;
   CInfoPBRec    MyCIPB;
   OSErrfErr;
   shorttheVol;
   Handle nameH;
   long theDir,foundDir;
   
   RememberA0();
   SetUpA4();
   
   if ((paramPtr->paramCount < 1) || 
 (paramPtr->paramCount > 2)) 
   {
   SysBeep(10);
   /* return error string */
   goto Done;
   }
   
 ZeroToPas(paramPtr,*((unsigned char **)           paramPtr->params[0]), 
fName);
   if (paramPtr->paramCount == 2)
   {
   ZeroToPas(paramPtr,*((unsigned char **)               paramPtr->params[1]),vName);
   if (vName[vName[0]] != ‘:’)
   {
   vName[0]++;
   vName[vName[0]] = ‘:’;
   }
 MyHPB.volumeParam.ioCompletion = Nil;
 MyHPB.volumeParam.ioNamePtr = vName;
 MyHPB.volumeParam.ioVRefNum = 0;
 MyHPB.volumeParam.ioVolIndex = -1;
 fErr = PBHGetVInfo(&MyHPB,False);
 if (fErr)
 {
        SysBeep(10);
        /* return error string */
        goto Done;
 }
 theVol = MyHPB.volumeParam.ioVRefNum;
 }
   else theVol = GetSysVol();
   
   MyCIPB.dirInfo.ioCompletion = 0L;
   MyCIPB.dirInfo.ioNamePtr = 0L;
   MyCIPB.dirInfo.ioVRefNum = theVol;
   MyCIPB.dirInfo.ioFDirIndex = 0;
   MyCIPB.dirInfo.ioDrDirID = 2L;
   fErr = PBGetCatInfo(&MyCIPB,False);
   
   if (fErr)
 {
   SysBeep(10);
   /* return error string */
   goto Done;
 }
 else
   {
   fErr = 
 SearchFile(2L,
 MyCIPB.dirInfo.ioDrNmFls,
 theVol,
 &fName,
 &foundDir);
   if (fErr)
 {
   SysBeep(10);
   /* return error string */
   goto Done;
 }
 
   fullPath[0] = 0;
   PstrCopy(fullPath,fName);
   
   MyCIPB.dirInfo.ioCompletion = Nil;
   MyCIPB.dirInfo.ioNamePtr = str;
   MyCIPB.dirInfo.ioVRefNum = theVol;
   MyCIPB.dirInfo.ioFDirIndex = -1;
   MyCIPB.dirInfo.ioDrDirID = foundDir;
   fErr = PBGetCatInfo(&MyCIPB,False);
   PrependStr(MyCIPB.dirInfo.ioNamePtr,fullPath);
   
   do {
   MyCIPB.dirInfo.ioDrDirID =
 MyCIPB.dirInfo.ioDrParID;
   fErr = PBGetCatInfo(&MyCIPB,False);
   if (fErr == noErr)
 PrependStr(MyCIPB.dirInfo.ioNamePtr,fullPath);
   } while (fErr == noErr);
   
   paramPtr->returnValue =  PasToZero(paramPtr,(StringPtr)fullPath);
   }

Done:
   RestoreA4();
   }
  
/*--------------------------------------------
SearchFile is the recursive hierarchical search engine.  It looks at 
all the files and then all the folders in the directory specified by 
theVol and theDir for the file specified by fName
--------------------------------------------*/
SearchFile(theDir,count,theVol,fName,foundDir)
 long   theDir;
   shortcount,theVol;
   Str255 *fName;
   long *foundDir;
   {
   shortI;
   OSErrfErr;
   Str255 str;
   CInfoPBPtr    MyCIPB;
   
   MyCIPB = (CInfoPBPtr)NewPtr(sizeof(CInfoPBRec));
   for (I=1;I<=count;I++)
   {
   str[0] = 0;
   MyCIPB->dirInfo.ioCompletion = Nil;
   MyCIPB->dirInfo.ioNamePtr = str;
   MyCIPB->dirInfo.ioVRefNum = theVol;
   MyCIPB->dirInfo.ioFDirIndex = I;
   MyCIPB->dirInfo.ioDrDirID = theDir;
   fErr = PBGetCatInfo(MyCIPB,False);
   if (fErr) 
   {
   SysBeep(10);
   return (fErr);
   }
   else
   {
   if (!(MyCIPB->dirInfo.ioFlAttrib &  0x10))
   {
   if (EqualString(fName,
 MyCIPB->dirInfo.ioNamePtr,
 False,True))
   {
   *foundDir = 
 MyCIPB->hFileInfo.ioFlParID;
   return (0);
   }
   }
   }
   }
   
   for (I=1;I<=count;I++)
   {
   str[0] = 0;
   MyCIPB->dirInfo.ioCompletion = Nil;
   MyCIPB->dirInfo.ioNamePtr = str;
   MyCIPB->dirInfo.ioVRefNum = theVol;
   MyCIPB->dirInfo.ioFDirIndex = I;
   MyCIPB->dirInfo.ioDrDirID = theDir;
   fErr = PBGetCatInfo(MyCIPB,False);
   if (fErr) 
   {
   SysBeep(10);
   return (fErr);
   }
   else
   {
   if (MyCIPB->dirInfo.ioFlAttrib & 0x10)
   {
   fErr = 
 SearchFile(
 MyCIPB->dirInfo.ioDrDirID,
   MyCIPB->dirInfo.ioDrNmFls,
   theVol,
   fName,
   foundDir);
   if (!fErr) return (0);
   }
   }
   }
   
   DisposPtr(MyCIPB);
   return (fnfErr);
   }

/*--------------------------------------------
PrependStr puts string s1 and a colon before string s2.
--------------------------------------------*/
PrependStr(s1,s2)
 char   *s1,*s2;
 {
 Str255 temp;
 PstrCopy(temp,s2);
 s1[0]++;
 s1[s1[0]] = ‘:’;
 PstrCopy(s2,s1);
 BlockMove(&(temp[1]),&(s2[s2[0]+1]),
 (long)temp[0]);
 s2[0] += temp[0];
 }

/*--------------------------------------------
PstrCopy copies string s2 into string s1
--------------------------------------------*/
PstrCopy(s1,s2)
 char   *s1,*s2;
 {
 short  len;
 for (len=*s2;len>=0;--len) *s1++ = *s2++;
 }

/*--------------------------------------------
GetSysVol returns the vRefNum of the startup system volume.
--------------------------------------------*/
GetSysVol()
   {
   shortvRefNum;
   OSErrFErr;
   FErr = GetVRefNum(SysMap,&vRefNum);
   return vRefNum;
   }

[Mark Armstrong is presently the Vice President of Technical Operations for Pharos Technologies, Inc., a system integration and software development firm. He is the author of UNITize™, and has contributed to several other projects such as Milo™ and Marble Madness™.]

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Whitethorn Games combines two completely...
If you have ever gone fishing then you know that it is a lesson in patience, sitting around waiting for a bite that may never come. Well, that's because you have been doing it wrong, since as Whitehorn Games now demonstrates in new release Skate... | Read more »
Call of Duty Warzone is a Waiting Simula...
It's always fun when a splashy multiplayer game comes to mobile because they are few and far between, so I was excited to see the notification about Call of Duty: Warzone Mobile (finally) launching last week and wanted to try it out. As someone who... | Read more »
Albion Online introduces some massive ne...
Sandbox Interactive has announced an upcoming update to its flagship MMORPG Albion Online, containing massive updates to its existing guild Vs guild systems. Someone clearly rewatched the Helms Deep battle in Lord of the Rings and spent the next... | Read more »
Chucklefish announces launch date of the...
Chucklefish, the indie London-based team we probably all know from developing Terraria or their stint publishing Stardew Valley, has revealed the mobile release date for roguelike deck-builder Wildfrost. Developed by Gaziter and Deadpan Games, the... | Read more »
Netmarble opens pre-registration for act...
It has been close to three years since Netmarble announced they would be adapting the smash series Solo Leveling into a video game, and at last, they have announced the opening of pre-orders for Solo Leveling: Arise. [Read more] | Read more »
PUBG Mobile celebrates sixth anniversary...
For the past six years, PUBG Mobile has been one of the most popular shooters you can play in the palm of your hand, and Krafton is celebrating this milestone and many years of ups by teaming up with hit music man JVKE to create a special song for... | Read more »
ASTRA: Knights of Veda refuse to pump th...
In perhaps the most recent example of being incredibly eager, ASTRA: Knights of Veda has dropped its second collaboration with South Korean boyband Seventeen, named so as it consists of exactly thirteen members and a video collaboration with Lee... | Read more »
Collect all your cats and caterpillars a...
If you are growing tired of trying to build a town with your phone by using it as a tiny, ineffectual shover then fear no longer, as Independent Arts Software has announced the upcoming release of Construction Simulator 4, from the critically... | Read more »
Backbone complete its lineup of 2nd Gene...
With all the ports of big AAA games that have been coming to mobile, it is becoming more convenient than ever to own a good controller, and to help with this Backbone has announced the completion of their 2nd generation product lineup with their... | Read more »
Zenless Zone Zero opens entries for its...
miHoYo, aka HoYoverse, has become such a big name in mobile gaming that it's hard to believe that arguably their flagship title, Genshin Impact, is only three and a half years old. Now, they continue the road to the next title in their world, with... | Read more »

Price Scanner via MacPrices.net

B&H has Apple’s 13-inch M2 MacBook Airs o...
B&H Photo has 13″ MacBook Airs with M2 CPUs and 256GB of storage in stock and on sale for up to $150 off Apple’s new MSRP, starting at only $849. Free 1-2 day delivery is available to most US... Read more
M2 Mac minis on sale for $100-$200 off MSRP,...
B&H Photo has Apple’s M2-powered Mac minis back in stock and on sale today for $100-$200 off MSRP. Free 1-2 day shipping is available for most US addresses: – Mac mini M2/256GB SSD: $499, save $... Read more
Mac Studios with M2 Max and M2 Ultra CPUs on...
B&H Photo has standard-configuration Mac Studios with Apple’s M2 Max & Ultra CPUs in stock today and on Easter sale for $200 off MSRP. Their prices are the lowest available for these models... Read more
Deal Alert! B&H Photo has Apple’s 14-inch...
B&H Photo has new Gray and Black 14″ M3, M3 Pro, and M3 Max MacBook Pros on sale for $200-$300 off MSRP, starting at only $1399. B&H offers free 1-2 day delivery to most US addresses: – 14″ 8... Read more
Department Of Justice Sets Sights On Apple In...
NEWS – The ball has finally dropped on the big Apple. The ball (metaphorically speaking) — an antitrust lawsuit filed in the U.S. on March 21 by the Department of Justice (DOJ) — came down following... Read more
New 13-inch M3 MacBook Air on sale for $999,...
Amazon has Apple’s new 13″ M3 MacBook Air on sale for $100 off MSRP for the first time, now just $999 shipped. Shipping is free: – 13″ MacBook Air (8GB RAM/256GB SSD/Space Gray): $999 $100 off MSRP... Read more
Amazon has Apple’s 9th-generation WiFi iPads...
Amazon has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80-$100 off MSRP, starting only $249. Their prices are the lowest available for new iPads anywhere: – 10″ 64GB WiFi iPad (Space Gray or... Read more
Discounted 14-inch M3 MacBook Pros with 16GB...
Apple retailer Expercom has 14″ MacBook Pros with M3 CPUs and 16GB of standard memory discounted by up to $120 off Apple’s MSRP: – 14″ M3 MacBook Pro (16GB RAM/256GB SSD): $1691.06 $108 off MSRP – 14... Read more
Clearance 15-inch M2 MacBook Airs on sale for...
B&H Photo has Apple’s 15″ MacBook Airs with M2 CPUs (8GB RAM/256GB SSD) in stock today and on clearance sale for $999 in all four colors. Free 1-2 delivery is available to most US addresses.... Read more
Clearance 13-inch M1 MacBook Airs drop to onl...
B&H has Apple’s base 13″ M1 MacBook Air (Space Gray, Silver, & Gold) in stock and on clearance sale today for $300 off MSRP, only $699. Free 1-2 day shipping is available to most addresses in... Read more

Jobs Board

Medical Assistant - Surgical Oncology- *Apple...
Medical Assistant - Surgical Oncology- Apple Hill Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Business Analyst | *Apple* Pay - Banco Popu...
Business Analyst | Apple PayApply now " Apply now + Apply Now + Start applying with LinkedIn Start + Please wait Date:Mar 19, 2024 Location: San Juan-Cupey, PR Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.