Q: How can I find out the directory ID and volume reference number for the
folder containing my application?
A: You can ask the Process Manager for this information by calling the
GetProcessInformation routine from inside of your application. The
directory ID and volume reference number can be extracted from the
FSSpec record filled out by the GetProcessInformation call.
The GetApplicationDirectory routine shown in Listing 1
illustrates how you would do this.
#include <Types.h>
#include <Files.h>
#include <Processes.h>
/* GetApplicationDirectory returns the volume reference number
and directory ID for the current application's directory. */
OSStatus GetApplicationDirectory(short *vRefNum, long *dirID) {
ProcessSerialNumber PSN;
ProcessInfoRec pinfo;
FSSpec pspec;
OSStatus err;
/* valid parameters */
if (vRefNum == NULL || dirID == NULL) return paramErr;
/* set up process serial number */
PSN.highLongOfPSN = 0;
PSN.lowLongOfPSN = kCurrentProcess;
/* set up info block */
pinfo.processInfoLength = sizeof(pinfo);
pinfo.processName = NULL;
pinfo.processAppSpec = &pspec;
/* grab the vrefnum and directory */
err = GetProcessInformation(&PSN, &pinfo);
if (err == noErr) {
*vRefNum = pspec.vRefNum;
*dirID = pspec.parID;
}
return err;
}
|
|
Listing 1. Extracting an application's location in the file system
from results returned by GetProcessInformation .
Q: Okay, now that I know how to find the directory containing the application, how
can I make sure this is the default directory?
A: Here, all you need to do is pass the volume reference number and
directory ID extracted from the results returned from
GetProcessInformation to the PBHSetVol routine. An
example of how to do this is shown in Listing 2.
#include <Types.h>
#include <Files.h>
#include <Processes.h>
/* SetApplicationDirAsDefault sets the default directory
to the directory containing the current application. */
OSStatus SetApplicationDirAsDefault(void) {
WDPBRec wpb;
OSStatus err;
err = GetApplicationDirectory(&wpb.ioVRefNum, &wpb.ioWDDirID);
if (err == noErr) {
wpb.ioNamePtr = NULL;
err = PBHSetVolSync(&wpb);
}
return err;
}
|
|
Listing 2. Setting the default directory to the directory containing
the application.
Q: Great! But what versions of the system software allow me to do this?
A: The techniques shown in Listing 1 and Listing 2 can be used in any
version of the system software from System 7 through Carbon.
|