CFG.PBI:
Code: Select all
Procedure.i FindLastDotInFilename(a.s)
CompilerIf #PB_Compiler_Unicode = 1
CompilerError "UNICODE NOT SUPPORTED - FindLastDotInFilename() function"
CompilerEndIf
Protected l=Len(a); using a global variable for 'l' would speed up the procedure
While l
l-1
Select PeekA(@a+1)
Case '.': ProcedureReturn l
Case '/','\': ProcedureReturn 0 ;we've found the folder root before the dot, so there is no dot
EndSelect
Wend
ProcedureReturn 0
EndProcedure
Procedure.s AppPath() ;IMPORTANT: Always includes a trailing slash (\ in Windows, / in Linux&Mac)
Static init, sVal.s
If init = 0
sVal = GetPathPart(ProgramFilename())
If Right(sVal,1) <> "\" And Right(sVal,1) <> "/"
CompilerIf #PB_Compiler_OS = #PB_OS_Windows
sVal = sVal + "\"
CompilerElse
sVal = sVal + "/"
CompilerEndIf
EndIf
init = 1
EndIf
ProcedureReturn sVal
EndProcedure
Procedure.s AppBaseFilename()
Static init, sVal.s
Protected aDot.i
If init = 0
sVal = ProgramFilename()
aDot = FindLastDotInFilename(sVal)
If aDot: sVal = Left(sVal, aDot): EndIf
init = 1
EndIf
ProcedureReturn sVal
EndProcedure
;------------------------------------------------------------------
Procedure SaveCFG(sGroup.s, sKey.s, sVal.s)
Protected sIniFile.s = AppBaseFilename() + ".cfg"
If OpenPreferences(sIniFile, #PB_Preference_NoSpace | #PB_Preference_GroupSeparator)
Else
If CreatePreferences(sIniFile, #PB_Preference_NoSpace | #PB_Preference_GroupSeparator)
Else
MessageRequester("Error", "Unable to open settings file " + sIniFile)
ProcedureReturn
EndIf
EndIf
PreferenceGroup(sGroup)
WritePreferenceString (sKey, sVal)
ClosePreferences()
EndProcedure
Procedure.s ReadCFG(sGroup.s, sKey.s)
Protected sIniFile.s = AppBaseFilename() + ".cfg"
Protected sResult.s
If OpenPreferences(sIniFile)
PreferenceGroup(sGroup)
sResult = ReadPreferenceString(sKey, "")
ClosePreferences()
Else
MessageRequester("Error", "Unable to open settings file " + sIniFile)
ProcedureReturn
EndIf
ProcedureReturn sResult
EndProcedure
Procedure.i CFGExists()
Protected sIniFile.s = AppBaseFilename() + ".cfg"
If FileSize(sIniFile) > 0: ProcedureReturn 1: EndIf
EndProcedure
Example:
Code: Select all
XIncludeFile("cfg.pbi")
;Save settings
SaveCFG("Settings", "My First Option", "My first value")
SaveCFG("Settings", "My Second Option", "My second value")
;Read setting
Debug("Stored value = " + ReadCFG("Settings", "My First Option"))
Debug("Stored value = " + ReadCFG("Settings", "My Second Option"))