home *** CD-ROM | disk | FTP | other *** search
Text File | 1997-06-30 | 2.7 KB | 116 lines | [TEXT/CWIE] |
- /*******************************************************************************\
- CPreferenceMgr - a class for managing preferences
- Dan Crevier 6/19/97 <mailto:Dan.Crevier@pobox.com>
-
- To add preferences to your application, make a subclass of CPreferenceMgr with
- member values for your prefs, and implement:
-
- Read(LFileStream &prefFile) - to read preferences from a stream, like:
- prefFile >> data1 >> data2
- Throw execptions if there is a problem with the data, and it will be
- flagged corrupt, and the default values will be used
- Write(LFileStream &prefFile) - to write the preferences to a stream, like:
- prefFile << data1 << data2
- ReportError(const LStr255 &errorString) - to report errors - like corrupt
- preferences
-
- In your application, add a member variable for your preferences. In the
- constructor, add:
-
- mPreferences = new CMyPrefs;
- mPreferences->Init("\pMy Pref file name", kMyCreator);
-
- In your destructor, add:
-
- mPreferences->FlushPreferences();
- delete mPreferences;
-
- And you can also flush the preferences at any other time, like when the
- user closes a preference dialog or something.
-
- Thanks to John C. Daub for lots of useful suggestions
-
- \*******************************************************************************/
-
- #include "CPreferenceMgr.h"
-
- #include <LFileStream.h>
- #include <LString.h>
-
- #include <Folders.h>
-
- CPreferenceMgr::CPreferenceMgr()
- : mInited(false)
- {
- }
-
- void CPreferenceMgr::Init(const LStr255 &prefName, OSType creatorSpec,
- OSType fileType)
- {
- OSErr err;
-
- // Find the preferences folder
- FailOSErr_(FindFolder(kOnSystemDisk, kPreferencesFolderType, kCreateFolder,
- &mPrefSpec.vRefNum, &mPrefSpec.parID));
-
- // Make an FSSpec to the preference file
- err = ::FSMakeFSSpec(mPrefSpec.vRefNum, mPrefSpec.parID, prefName, &mPrefSpec);
-
- LFileStream prefFile(mPrefSpec);
-
- mInited = true;
-
- if (err == fnfErr) // file does not exist yet
- {
- prefFile.CreateNewDataFile(creatorSpec, fileType);
- SetDefaultPreferences();
- FlushPreferences();
- }
- else if (err == noErr)
- {
- try
- {
- prefFile.OpenDataFork(fsRdPerm);
- Read(prefFile);
- }
- catch(...)
- {
- ReportError("\pPreferences were corrupt. Default values used.");
- SetDefaultPreferences();
- }
- }
- else
- {
- FailOSErr_(err);
- }
- }
-
- CPreferenceMgr::~CPreferenceMgr()
- {
- }
-
- // write the preferences to disk
- void CPreferenceMgr::FlushPreferences()
- {
- Assert_(mInited);
- try
- {
- LFileStream prefFile(mPrefSpec);
-
- prefFile.OpenDataFork(fsRdWrPerm);
- prefFile.SetLength(0);
-
- Write(prefFile);
- }
- catch(...)
- {
- ReportError("\pThere was an error writing the preferences to disk.");
- }
- }
-
- // override this to use whatever mechanism you use to report errors
- void CPreferenceMgr::ReportError(const LStr255 &/*errorString*/)
- {
- // ::DebugStr(errorString);
- }
-