Update an existing INI file with values from an updated INI file

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


Description

This script will update an existing INI file on a user's computer with new values from a new INI file.

Example

INI file new.ini

[section]
key1=hello there
key3=Afrow UK

INI file old.ini (to be updated)

[section]
key1=good day
key2=my name is
key3=Jimbobo

Using

Push "$INSTDIR\new.ini"
Push "$INSTDIR\old.ini"
 Call ReadINIFileKeys

Result

[section]
key1=hello there
key2=my name is
key3=Afrow UK

Usage

Push "read-from.ini"
Push "write-to.ini"
 Call ReadINIFileKeys

The Function

Note that this function requires the TrimNewLines & SplitFirstStrPart functions to be in your script as well.

 Function ReadINIFileKeys
      Exch $R0 ;INI file to write
      Exch
      Exch $R1 ;INI file to read
      Push $R2
      Push $R3
      Push $R4 ;uni var
      Push $R5 ;uni var
      Push $R6 ;last INI section
      ClearErrors ; So we don't error out for nonrelated reasons
      FileOpen $R2 $R1 r
 
      Loop:
       FileRead $R2 $R3   ;get next line into R3
       IfErrors Exit
 
       Push $R3
        Call StrTrimNewLines 
       Pop $R3
 
       StrCmp $R3 "" Loop   ;if blank line, skip
 
       StrCpy $R4 $R3 1   ;get first char into R4
       StrCmp $R4 ";" Loop   ;check it for semicolon and skip line if so(ini comment)
 
       StrCpy $R4 $R3 "" -1   ;get last char of line into R4
       StrCmp $R4 "]" 0 +6     ;if last char is ], parse section name, else jump to parse key/value
       StrCpy $R6 $R3 -1   ;get all except last char
       StrLen $R4 $R6     ;get str length
       IntOp $R4 $R4 - 1    ;subtract one from length
       StrCpy $R6 $R6 "" -$R4   ;copy all but first char to trim leading [, placing the section name in R6
      Goto Loop
 
       Push "="  ;push delimiting char
       Push $R3
        Call SplitFirstStrPart
       Pop $R4
       Pop $R5       
 
       WriteINIStr $R0 $R6 $R4 $R5      
 
      Goto Loop
      Exit:
 
      FileClose $R2
 
      Pop $R6
      Pop $R5
      Pop $R4
      Pop $R3
      Pop $R2
      Pop $R1
      Pop $R0
     FunctionEnd

Written by me (Afrow UK) for VegetaSan in this topic.