Read from INI style file without section headers

From NSIS Wiki
Jump to navigationJump to search
Author: Afrow UK (talk, contrib)


Description

This function will read values from an INI type file that does not have section headers (e.g. [blah]). Note that this function also requires the StrTrimNewLines function to be present in your script.

Note: For standard INI files, use NSIS's ReadINIStr.

Now also available: WriteINIStrNS.

Alternative solution

A macro called ConfigRead has been introduced into the main distribution of NSIS. NSIS Manual, Appendix E, ConfigRead

Usage

${ReadINIStrNS} $R0 "$INSTDIR\file.ext" "key"
; $R0 = key value or rogue "no value!" if no key was found / error occured

The Function

Function ReadINIStrNS
 Exch $R0 ; key
 Exch
 Exch $R1 ; ini file
 Push $R2 ; ini file handle
 Push $R3 ; key len
 Push $R4
 Push $R5
 
  FileOpen $R2 $R1 r
   IfErrors End
 
  StrLen $R3 $R0
  IntOp $R3 $R3 + 1 ; inc. "="
 
  LoopRead:
   ClearErrors
   FileRead $R2 $R1
   IfErrors End
 
   StrCpy $R4 $R1 $R3
   StrCmp $R4 "$R0=" 0 LoopRead
 
  StrLen $R5 $R1
  IntOp $R3 $R5 - $R3
  StrCpy $R0 $R1 "" -$R3
 
   Push $R0
    Call StrTrimNewLines
   Pop $R0
 
  Goto +2
 
 End:
  StrCpy $R0 "no value!"
 
  FileClose $R2
 
 Pop $R5
 Pop $R4
 Pop $R3
 Pop $R2
 Pop $R1
 Exch $R0 ; output value
FunctionEnd
 
!define ReadINIStrNS "!insertmacro ReadINIStrNS"
!macro ReadINIStrNS Var File Key
 Push "${File}"
 Push "${Key}"
  Call ReadINIStrNS
 Pop "${Var}"
!macroend

-Stu (Afrow UK)