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

Summon your guild and prepare for war in...
Netmarble is making some pretty big moves with their latest update for Seven Knights Idle Adventure, with a bunch of interesting additions. Two new heroes enter the battle, there are events and bosses abound, and perhaps most interesting, a huge... | Read more »
Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »
MoreFun Studios has announced Season 4,...
Tension has escalated in the ever-volatile world of Arena Breakout, as your old pal Randall Fisher and bosses Fred and Perrero continue to lob insults and explosives at each other, bringing us to a new phase of warfare. Season 4, Into The Fog of... | Read more »
Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links below... | Read more »
Marvel Future Fight celebrates nine year...
Announced alongside an advertising image I can only assume was aimed squarely at myself with the prominent Deadpool and Odin featured on it, Netmarble has revealed their celebrations for the 9th anniversary of Marvel Future Fight. The Countdown... | Read more »
HoYoFair 2024 prepares to showcase over...
To say Genshin Impact took the world by storm when it was released would be an understatement. However, I think the most surprising part of the launch was just how much further it went than gaming. There have been concerts, art shows, massive... | Read more »

Price Scanner via MacPrices.net

Amazon is offering a $100 discount on every M...
Amazon is offering a $100 instant discount on each configuration of Apple’s new 13″ M3 MacBook Air, in Midnight, this weekend. These are the lowest prices currently available for new 13″ M3 MacBook... Read more
You can save $300-$480 on a 14-inch M3 Pro/Ma...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more
24-inch M1 iMacs available at Apple starting...
Apple has clearance M1 iMacs available in their Certified Refurbished store starting at $1049 and ranging up to $300 off original MSRP. Each iMac is in like-new condition and comes with Apple’s... Read more
Walmart continues to offer $699 13-inch M1 Ma...
Walmart continues to offer new Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBook for sale by... Read more
B&H has 13-inch M2 MacBook Airs with 16GB...
B&H Photo has 13″ MacBook Airs with M2 CPUs, 16GB of memory, and 256GB of storage in stock and on sale for $1099, $100 off Apple’s MSRP for this configuration. Free 1-2 day delivery is available... Read more
14-inch M3 MacBook Pro with 16GB of RAM avail...
Apple has the 14″ M3 MacBook Pro with 16GB of RAM and 1TB of storage, Certified Refurbished, available for $300 off MSRP. Each MacBook Pro features a new outer case, shipping is free, and an Apple 1-... Read more
Apple M2 Mac minis on sale for up to $150 off...
Amazon has Apple’s M2-powered Mac minis in stock and on sale for $100-$150 off MSRP, each including free delivery: – Mac mini M2/256GB SSD: $499, save $100 – Mac mini M2/512GB SSD: $699, save $100 –... Read more
Amazon is offering a $200 discount on 14-inch...
Amazon has 14-inch M3 MacBook Pros in stock and on sale for $200 off MSRP. Shipping is free. Note that Amazon’s stock tends to come and go: – 14″ M3 MacBook Pro (8GB RAM/512GB SSD): $1399.99, $200... Read more
Sunday Sale: 13-inch M3 MacBook Air for $999,...
Several Apple retailers have the new 13″ MacBook Air with an M3 CPU in stock and on sale today for only $999 in Midnight. These are the lowest prices currently available for new 13″ M3 MacBook Airs... Read more
Multiple Apple retailers are offering 13-inch...
Several Apple retailers have 13″ MacBook Airs with M2 CPUs in stock and on sale this weekend starting at only $849 in Space Gray, Silver, Starlight, and Midnight colors. These are the lowest prices... Read more

Jobs Board

Relationship Banker - *Apple* Valley Financ...
Relationship Banker - Apple Valley Financial Center APPLE VALLEY, Minnesota **Job Description:** At Bank of America, we are guided by a common purpose to help Read more
IN6728 Optometrist- *Apple* Valley, CA- Tar...
Date: Apr 9, 2024 Brand: Target Optical Location: Apple Valley, CA, US, 92308 **Requisition ID:** 824398 At Target Optical, we help people see and look great - and Read more
Medical Assistant - Orthopedics *Apple* Hil...
Medical Assistant - Orthopedics Apple Hill York Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Now Read more
*Apple* Systems Administrator - JAMF - Activ...
…**Public Trust/Other Required:** None **Job Family:** Systems Administration **Skills:** Apple Platforms,Computer Servers,Jamf Pro **Experience:** 3 + years of Read more
Liquor Stock Clerk - S. *Apple* St. - Idaho...
Liquor Stock Clerk - S. Apple St. Boise Posting Begin Date: 2023/10/10 Posting End Date: 2024/10/14 Category: Retail Sub Category: Customer Service Work Type: Part Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.