TGC Codebase Backup



Reading INI file data by Ade

15th Feb 2005 19:25
Summary

GetIniValue, GetIniString, GetAppIniFile



Description

Support reading in of structured configuration data from an .ini file complete with [Sections] and Key=value entries:

GetAppIniFile - if app is called demo.exe will return demo.ini

GetIniValue - get the numeric value of the required key from a given section - if not exists then the specified default value is returned

GetIniString - get the text of the required key from a given section - if not exists then the specified default value is returned



Code
                                    ` This code was downloaded from The Game Creators
                                    ` It is reproduced here with full permission
                                    ` http://www.thegamecreators.com
                                    
                                    #constant INI_FILE_NUMBER     32

function GetAppIniFile()
   temp$ = appname$()
   for i = len(temp$) to 1 step -1
      if mid$(temp$, i) = "."
         temp$ = left$(temp$, i) + "ini"
         exitfunction temp$
      endif
   next
endfunction ""

function GetIniValue(IniFile$, section$, key$, default)
   temp$ = GetIniString(IniFile$, section$, key$, "")
   if temp$ <> ""
      value = val(temp$)
      exitfunction value
   endif
endfunction default

function GetIniString(IniFile$, section$, key$, default$)
   FoundSection = 0
   section$ = "[" + section$ + "]"
   SectionLength = Len(section$)
   key$ = key$ + "="
   KeyLength = Len(key$)

   open to read INI_FILE_NUMBER, IniFile$
   while (file end(INI_FILE_NUMBER) = 0)
      read string INI_FILE_NUMBER, temp$

      rem if we had found the required section and now have reached another section finish
      if (FoundSection = 1) and (mid$(temp$, 1) = "[")
         close file INI_FILE_NUMBER
         exitfunction default$
      endif

      rem have we found the start of the section
      if left$(temp$, SectionLength) = section$
         FoundSection = 1
      rem are we in a section looking for the key
      else
         if FoundSection = 1
            rem check for key found
            if left$(temp$, KeyLength) = key$
               temp$ = right$(temp$, Len(temp$) - KeyLength)
               close file INI_FILE_NUMBER
               exitfunction temp$
            endif
         endif
      endif
   endwhile
   close file INI_FILE_NUMBER
endfunction default$