Jump to content

IniEx UDF


FichteFoll
 Share

Recommended Posts

IniEx.au3 (Version 1.0 _ )

I've been working on this just ago and thought that sharing it would be a nice thing to start with. I needed those functions from time to time and then decided to create them.

So, what does it actually do?

- You can change the text file encoding from ANSI to Unicode and back to ANSI and then can use AutoIt's bulit-in ini-functions to read Unicode out of an ini file.

- You can read the whole ini into one threedimensional array including all sections and its keys and values. You can also write an whole ini out of an array.

- You can read ini data from a string, useful if you don't want to create a new file after using InetRead or anything like that what includes reading from memory.

I don't really think that writing into a string would be that useful but I could make those functions right away if you request them.

List of functions:

; #CURRENT# =====================================================================================================================
; _IniConvertToUnicode              Converts encoding format of a text file to UTF-16 Little Endian
; _IniConvertToANSI                 Converts encoding format of a text file to ANSI
; _IniReadToArray                   Returns the whole ini file into one array with three dimensions
; _IniWriteFromArray                Writes or creates an Ini out of an array
; _IniReadFromString                Returns the value of a key in a specific section of an ini-formatted string
; _IniReadSectionNamesFromString    Returns all keys and its values from a given section name of an ini-formatted string
; _IniReadSectionFromString         Returns all section names of an ini-formatted string
; _IniReadToArrayFromString         Returns the whole ini file into one array with three dimensions
; ===============================================================================================================================

I added examples for every function but below you will find an example using more than one or two functions.

Source:

#include-once

; #INDEX# =======================================================================================================================
; Title .........: IniEx (1.0)
; Date ..........: 06.02.2011
; AutoIt Version : 3.3 + (development version = 3.3.6.0)
; Language ......: English
; Description ...: Extra functions for an extended ini support:
;                  - Functions to change the ini's encoding format and allow to use
;                    unicode for all ini-functions, prefered UTF-16 Little Endian since it's the fastest in AutoIt
;                  - Functions to read and write a whole ini into or from one three-dimensional array; also from a string
;                  - Functions to read keys, sections and sectionnames from a string instead of a file
; Remarks .......:
; Link ..........: http://www.autoitscript.com/forum/topic/125163-iniex-udf/
; Author ........: FichteFoll
; ===============================================================================================================================


; #CHANGELOG# ===================================================================================================================
;
; ===============================================================================================================================

; #CURRENT# =====================================================================================================================
; _IniConvertToUnicode              Converts encoding format of a text file to UTF-16 Little Endian
; _IniConvertToANSI                 Converts encoding format of a text file to ANSI
; _IniReadToArray                   Returns the whole ini file into one array with three dimensions
; _IniWriteFromArray                Writes or creates an Ini out of an array
; _IniReadFromString                Returns the value of a key in a specific section of an ini-formatted string
; _IniReadSectionNamesFromString    Returns all keys and its values from a given section name of an ini-formatted string
; _IniReadSectionFromString         Returns all section names of an ini-formatted string
; _IniReadToArrayFromString         Returns the whole ini file into one array with three dimensions
; ===============================================================================================================================

; #INTERNAL_USE_ONLY# ===========================================================================================================
; __StringEscapeRegExp
; ===============================================================================================================================

; ###############################################################################################################################

; ###############################################################################################################################

;#Function# =====================================================================================================================
; Name............: _IniConvertToUnicode
; Description.....: Converts encoding format of a text file to UTF-16 Little Endian
; Syntax..........: _IniConvertToUnicode($szFile, $fCreate = True)
; Parameters......:
;                   $szFile      - Path to text file (won't work with binary encoded files)
;                   $fCreate     - [optional]  The File will be created if it does not exist (default)
; Return values ..:
;                   Success      - Returns 1 - sets @extended = 1 if the file is already encoded correctly
;                   Failure      - Returns 0 - sets @error
;                                              | 1 - The file does not exist (requires $fCreate = False)
;                                              | 2 - The file is not a text file
;                                              | 3 - Reading the file failed
;                                              | 4 - Opening the file with unicode failed
;                                              | 5 - Writing the file with unicode failed
; Author .........: FichteFoll
; Remarks ........: Use the related functions and _IniReadToArray or _IniWriteFromArray to access a unicode-formatted ini.
;                   If the file does not exist it will be created.
; Related ........: FileGetEncoding, IniRead, IniWrite, IniReadSection, IniWriteSection, IniReadSectionNames
; Link ...........; See on top
; Example ........; _IniConvertToUnicode("c:/file.ini")
; ===============================================================================================================================
Func _IniConvertToUnicode($szFile, $fCreate = True)
    If Not FileExists($szFile) And $fCreate = False Then Return SetError(1)

    Local $iEncoding, $szContent, $f
    $iEncoding = FileGetEncoding($szFile)

    Switch $iEncoding
        Case 32
            Return SetExtended(1, 1) ; Nothing to be done
        Case -1
            If FileExists($szFile) Then SetError(2)
            ContinueCase
        Case Else
            $szContent = FileRead($szFile)
            If @error And FileExists($szFile) Then Return SetError(3)
            $f = FileOpen($szFile, 2 + 8 + 32) ; delete, create, utf-16 le
            If $f = -1 Then Return SetError(4)
            If FileWrite($f, $szContent) = 0 Then SetError(5, FileClose($f) * 0)
            FileClose($f)

            Return 1
    EndSwitch
EndFunc   ;==>_IniConvertToUnicode

;#Function# =====================================================================================================================
; Name............: _IniConvertToANSI
; Description.....: Converts encoding format of a text file to ANSI
; Syntax..........: _IniConvertToANSI($szFile, $fCreate = True)
; Parameters......:
;                   $szFile      - Path to text file (won't work with binary encoded files)
;                   $fCreate     - [optional]  The File will be created if it does not exist (default)
; Return values ..:
;                   Success      - Returns 1 - sets @extended = 1 if the file is already encoded correctly
;                   Failure      - Returns 0 - sets @error
;                                              | 1 - The file does not exist (requires $fCreate = False)
;                                              | 2 - The file is not a text file
;                                              | 3 - Reading the file failed
;                                              | 4 - Opening the file with ANSI failed
;                                              | 5 - Writing the file with ANSI failed
; Author .........: FichteFoll
; Modified........:
; Remarks ........: This is the oppsite of _IniConvertToUnicode. Characters that are Uincode-only will be converted to '?'.
; Related ........: FileGetEncoding, IniRead, IniWrite, IniReadSection, IniWriteSection, IniReadSectionNames
; Link ...........; See on top
; Example ........; _IniConvertToANSI("c:/file.ini")
; ===============================================================================================================================
Func _IniConvertToANSI($szFile, $fCreate = True)
    If Not FileExists($szFile) And $fCreate = False Then Return SetError(1)

    Local $iEncoding, $szContent, $f
    $iEncoding = FileGetEncoding($szFile)

    Switch $iEncoding
        Case 0
            Return SetExtended(1, 1) ; Nothing to be done
        Case -1
            If FileExists($szFile) Then SetError(2)
            ContinueCase
        Case Else
            $szContent = FileRead($szFile)
            If @error And FileExists($szFile) Then Return SetError(3)
            $f = FileOpen($szFile, 2 + 8 + 0) ; delete, create, ansi
            If $f = -1 Then Return SetError(4)
            If FileWrite($f, $szContent) = 0 Then SetError(5)
            FileClose($f)

            Return 1
    EndSwitch
EndFunc   ;==>_IniConvertToANSI

; ###############################################################################################################################

;#Function# ============================================================================================================================================
; Name............: _IniReadToArray
; Description.....: Returns the whole ini file into one array with three dimensions
; Syntax..........: _IniReadToArray($szFile)
; Parameters......:
;                   $szFile      - Path to the ini file
; Return values ..:
;                   Success      - Returns an array containing all sections, keys and values (see Remarks)
;                   Failure      - Returns 0 and sets @error = 1 if the section names could not be determined
; Author .........: FichteFoll
; Modified........:
; Remarks ........: On success the array has the following structure:
;                      [0][0][0] = section count
;                      [n][0][0] = nth Section name
;                      [n][0][1] = nth Section's key count
;                      [n][m][0] = nth Section's mth key's name (just like IniReadSection)
;                      [n][m][1] = nth Section's mth key's value (just like IniReadSection)
;                   If some sections could not be allocated, its key count is set to 0 which also happens if there is no key in the section.
;                   Check @extended for the total count of sections that could not be read or have 0 keys inside.
; Related ........: _IniWriteFromArray, IniReadSectionNames, IniReadSection
; Link ...........; See on top
; Example ........; $aArray = _IniReadToArray("c:\file.ini")
;                   For $i = 1 To $aArray[0][0][0]
;                       ConsoleWrite(StringFormat("! [%s]", $aArray[$i][0][0]) & @CRLF)
;                       For $j = 1 To $aArray[$i][0][1]
;                           ConsoleWrite(StringFormat("- %s=%s", $aArray[$i][$j][0], $aArray[$i][$j][1]) & @CRLF)
;                       Next
;                   Next
; ======================================================================================================================================================
Func _IniReadToArray($szFile)
    Local $aszSections, $aReturn[1], $aszSection, $iMaxKeys = 1, $ext

    $aszSections = IniReadSectionNames($szFile)
    If @error Then Return SetError(1)

    ReDim $aReturn[$aszSections[0] + 1][$iMaxKeys + 1][2]
    $aReturn[0][0][0] = $aszSections[0]

    For $i = 1 To $aszSections[0]
        $aReturn[$i][0][0] = $aszSections[$i]

        $aszSection = IniReadSection($szFile, $aszSections[$i])
        If @error Then ; ususally no errors here, just go to next section in that case
            $aReturn[$i][0][1] = 0
            $ext += 1
            ContinueLoop
        EndIf

        $aReturn[$i][0][1] = $aszSection[0][0]
        If $aszSection[0][0] > $iMaxKeys Then
            $iMaxKeys = $aszSection[0][0]
            ReDim $aReturn[$aszSections[0] + 1][$iMaxKeys + 1][2]
        EndIf
        For $j = 1 To $aszSection[0][0]
            $aReturn[$i][$j][0] = $aszSection[$j][0]
            $aReturn[$i][$j][1] = $aszSection[$j][1]
        Next
    Next

    Return SetExtended($ext, $aReturn)
EndFunc   ;==>_IniReadToArray

;#Function# =====================================================================================================================
; Name............: _IniWriteFromArray
; Description.....: Writes or creates an Ini out of an array
; Syntax..........: _IniWriteFromArray($szFile, Const ByRef $aArray, $fUnicode = False, $fDelete = True)
; Parameters......:
;                   $szFile      - Path to the ini file
;       Const ByRef $aArray      - The array containing the ini data; with three dimensions, 2 elements in the third and the following format:
;                                   [0][0][0|1] - not relevant, can contain values from _IniReadToArray
;                                  ![n][0][0] - nth section name
;                                   [n][0][1] - not relevant, can contain value from _IniReadToArray
;                                  ![n][m][0] - nth section's mth key name
;                                  ![n][m][1] - nth section's mth key value
;                   $fUnicode    - [optional] The ini will be encoded with Unicode using _IniConvertToUnicode
;                   $fDelete     - [optional] The whole file gets deleted before the array will be written into it;
;                                             sections will always be overwritten
; Return values ..:
;                   Success      - Returns 1
;                   Failure      - Returns 0 - sets @error
;                                              | 1 - Array is badly formatted
;                                              | 2 - Ini could not be converted to Unicode
;                                              | 3 - Every section has failed to be written
; Author .........: FichteFoll
; Remarks ........: This function is the opposite of _IniReadToArray and compatible with its return value.
;                   If a section fails to be written @extended is set to the total count of failures.
;                   If @extended is going to be the total count of sections @error is set to 3 and 0 returned.
; Related ........: _IniReadFromArray, IniWriteSection
; Link ...........; See on top
; Example ........; $aArray = _IniReadToArray("c:\file.ini")
;                   $aArray[1][1][1] = "the first value of this ini has changed"
;                   _IniWriteFromArray("c:\file2.ini", $aArray, True)
; ===============================================================================================================================
Func _IniWriteFromArray($szFile, Const ByRef $aArray, $fUnicode = False, $fDelete = True)
    If UBound($aArray, 0) <> 3 Or UBound($aArray, 3) <> 2 Then Return SetError(1) ; bad formatted
    If $fDelete Then FileDelete($szFile)
    If $fUnicode Then
        _IniConvertToUnicode($szFile)
        If @error Then Return SetError(2)
    EndIf

    Local $ext = 0

    For $i = 1 To UBound($aArray, 1) - 1
        Local $aszSection[1][2]

        For $j = 1 To UBound($aArray, 2) - 1
            If $aArray[$i][$j][0] = "" And $aArray[$i][$j][1] = "" Then ExitLoop ; empty entry
            ReDim $aszSection[$j+1][2]
            $aszSection[$j][0] = $aArray[$i][$j][0]
            $aszSection[$j][1] = $aArray[$i][$j][1]
        Next

        IniWriteSection($szFile, $aArray[$i][0][0], $aszSection)
        If @error Then $ext += 1
    Next

    If $ext = UBound($aArray, 1) Then Return SetError(3)
    Return SetExtended($ext, 1)
EndFunc   ;==>_IniWriteFromArray

; ###############################################################################################################################

;#Function# =====================================================================================================================
; Name............: _IniReadFromString
; Description.....: Returns the value of a key in a specific section of an ini-formatted string
; Syntax..........: _IniReadFromString($szInput, $szSection, $szKey, $Default)
; Parameters......:
;                   $szInput     - The string that contains data in ini format
;                   $szSection   - The sectionname (just as in IniRead)
;                   $szKey       - The keyname (just as in IniRead)
;                   $Default     - The default value if the key does not exist or reading failed (just as in IniRead)
; Return values ..:
;                   Success      - Returns the read value
;                   Failure      - Returns $Default
; Author .........: FichteFoll
; Remarks ........: Works for Unicode as well as for ANSI
; Related ........: IniRead, _IniReadSectionFromString
; Link ...........; See on top
; Example ........; $var = _IniReadFromString(StringFormat("[Sect]\r\nMyKey1=value1\r\nMyKey2=value2"), "Sect", "MyKey2", "no_value")
; ===============================================================================================================================
Func _IniReadFromString($szInput, $szSection, $szKey, $Default)
    $szInput = StringStripCR($szInput)
    Local $aRegMl = StringRegExp($szInput, "\[" & __StringEscapeRegExp($szSection) & "\]\n+(?:[^\[].*?=.*\n)*" & __StringEscapeRegExp($szKey) & "=(.*)\n?(", 3)
    If @error Then Return SetError(1, 0, $Default) ; key not found

    Return $aRegMl[0]
EndFunc   ;==>_IniReadFromString

;#Function# =====================================================================================================================
; Name............: _IniReadSectionNamesFromString
; Description.....: Returns all section names of an ini-formatted string
; Syntax..........: _IniReadSectionNamesFromString($szInput)
; Parameters......:
;                   $szInput     - The string that contains data in ini format
; Return values ..:
;                   Success      - Returns an array containing the section names; $result[0] contains the number of sections
;                   Failure      - Returns 0 and sets @error = 1 which means that no sections were found, this can have several reasons
; Author .........: FichteFoll
; Remarks ........: A section does not have to contain keys
; Related ........: IniReadSectionNames, IniReadSection
; Link ...........; See on top
; Example ........; $result = _IniReadSectionNamesFromString(StringFormat("[Sect]\r\nMyKey1=value1\r\nMyKey2=value2"), "Sect", "MyKey2", "no_value")
; ===============================================================================================================================
Func _IniReadSectionNamesFromString($szInput)
    $szInput = StringStripCR($szInput)
    Local $aRegMl = StringRegExp($szInput, "(?<=\n|\A)\[(.*)\](?!.|\Z)", 3)
    If @error Then Return SetError(1) ; nothing found

    Local $iUBound = UBound($aRegMl), $aReturn[$iUBound + 1]
    $aReturn[0] = $iUBound
    For $i = 0 To $iUBound - 1
        $aReturn[$i + 1] = $aRegMl[$i]
    Next

    Return $aReturn
EndFunc   ;==>_IniReadSectionNamesFromString

;#Function# =====================================================================================================================
; Name............: _IniReadSectionFromString
; Description.....: Returns all keys and its values from a given section name of an ini-formatted string
; Syntax..........: _IniReadSectionFromString($szInput, $szSection)
; Parameters......:
;                   $szInput     - The string that contains data in ini format
;                   $szSection   - The section name
; Return values ..:
;                   Success      - Returns an array containing the data;
;                                  $result[0][0] will contain the number of sectins, [n][0] the key and [n][1] the value
;                   Failure      - Returns 0 and sets @error = 1 meaning that the section was not found
; Author .........: FichteFoll
; Remarks ........: [0][0] can be 0 if the section has no keys, the array will not have any more elements
; Related ........: IniReadSection, IniWriteSection
; Link ...........; See on top
; Example ........; $result = _IniReadSectionFromString(StringFormat("[Sect]\r\nMyKey1=value1\r\nMyKey2=value2"), "Sect")
; ===============================================================================================================================
Func _IniReadSectionFromString($szInput, $szSection)
    ; Using RegExp rarely does not work; using workaround by parsing the lines into an array instead

;~  $szInput = StringStripCR(StringRegExpReplace($szInput, "\r(?!\n)", "\r\n"))
;~  Local $aRegMl = StringRegExp($szInput, "(?<=\n|\A)\[" & __StringEscapeRegExp($szSection) & "\](?:\n+?(.*?)=(.*))+(?=\n?\Z|\n\[)", 1)
;~  ;Local $aRegMl = StringRegExp($szInput, "(?:\n+?(.*?)=(.*))+", 3)

;~  ;Local $aRegMl = StringRegExp($szInput, "(?:\n(.*?)=(.*))", 3)
;~  If @error Then Return SetError(1) ; section not found
;~  ;_ArrayDisplay($aRegMl)

;~  Local $iUBound = UBound($aRegMl), $aReturn[$iUBound / 2 + 1][2]
;~  $aReturn[0][0] = $iUBound / 2

;~  For $i = 0 To $iUBound - 1
;~      Switch Mod($i, 2)
;~          Case 0
;~              $aReturn[Floor(($i) / 2) + 1][0] = $aRegMl[$i]
;~          Case 1
;~              $aReturn[Floor(($i) / 2) + 1][1] = $aRegMl[$i]
;~      EndSwitch
;~  Next

;~  Return $aReturn

    $szInput = StringStripCR(StringRegExpReplace($szInput, "\r(?!\n)", "\r\n"))
    Local $aszLines = StringSplit($szInput, @LF), $aReturn[1][2] = [[0, 0]], $fFound = False, $aRegMl, $j = 0

    For $i = 1 To $aszLines[0]
        If $aszLines[$i] = StringFormat("[%s]", $szSection) Then
            $fFound = True
            ContinueLoop
        EndIf
        If $fFound Then
            $aRegMl = StringRegExp($aszLines[$i], "(.*?)=(.*)", 1)
            If @error Then ExitLoop
            $j += 1
            $aReturn[0][0] = $j
            ReDim $aReturn[$aReturn[0][0] + 1][2]
            $aReturn[$j][0] = $aRegMl[0]
            $aReturn[$j][1] = $aRegMl[1]
        EndIf
    Next
    If $fFound = False Then Return SetError(1)
    ;If $j = 0 Then Return SetError(2) ; return empty array instead

    Return $aReturn
EndFunc   ;==>_IniReadSectionFromString

;#Function# ============================================================================================================================================
; Name............: _IniReadToArrayFromString
; Description.....: Returns the whole ini file into one array with three dimensions
; Syntax..........: _IniReadToArrayFromString($szFile)
; Parameters......:
;                   $szInput      - The string that contains data in ini format
; Return values ..:
;                   Success      - Returns an array containing all sections, keys and values (see Remarks)
;                   Failure      - Returns 0 and sets @error = 1 if the section names could not be determined
; Author .........: FichteFoll
; Modified........:
; Remarks ........: On success the array has the following structure:
;                      [0][0][0] = section count
;                      [n][0][0] = nth Section name
;                      [n][0][1] = nth Section's key count
;                      [n][m][0] = nth Section's mth key's name (just like IniReadSection)
;                      [n][m][1] = nth Section's mth key's value (just like IniReadSection)
;                   If some sections could not be allocated, its key count is set to 0 which also happens if there is no key in the section.
;                   Check @extended for the total count of sections that could not be read or have 0 keys inside.
; Related ........: _IniReadToArray, _IniWriteToArray, _IniReadSectionNamesFromString, _IniReadSectionFromString
; Link ...........; See on top
; Example ........; $aArray = _IniReadToArrayFromString(StringFormat("[Sect]\r\nMyKey1=value1\r\nMyKey2=value2\r\n[Sect_2]\r\nYourKey1=value1"))
;                   For $i = 1 To $aArray[0][0][0]
;                       ConsoleWrite(StringFormat("! [%s]", $aArray[$i][0][0]) & @CRLF)
;                       For $j = 1 To $aArray[$i][0][1]
;                           ConsoleWrite(StringFormat("- %s=%s", $aArray[$i][$j][0], $aArray[$i][$j][1]) & @CRLF)
;                       Next
;                   Next
; ======================================================================================================================================================
Func _IniReadToArrayFromString($szInput)
    Local $aszSections, $aReturn[1], $aszSection, $iMaxKeys = 1, $ext

    $aszSections = _IniReadSectionNamesFromString($szInput)
    If @error Then Return SetError(1)

    ReDim $aReturn[$aszSections[0] + 1][$iMaxKeys + 1][2]
    $aReturn[0][0][0] = $aszSections[0]

    For $i = 1 To $aszSections[0]
        $aReturn[$i][0][0] = $aszSections[$i]

        $aszSection = _IniReadSectionFromString($szInput, $aszSections[$i])
        If @error Then ; ususally no errors here, just go to next section in that case
            $aReturn[$i][0][1] = 0
            $ext += 1
            ContinueLoop
        EndIf

        $aReturn[$i][0][1] = $aszSection[0][0]
        If $aszSection[0][0] > $iMaxKeys Then
            $iMaxKeys = $aszSection[0][0]
            ReDim $aReturn[$aszSections[0] + 1][$iMaxKeys + 1][2]
        EndIf
        For $j = 1 To $aszSection[0][0]
            $aReturn[$i][$j][0] = $aszSection[$j][0]
            $aReturn[$i][$j][1] = $aszSection[$j][1]
        Next
    Next

    Return SetExtended($ext, $aReturn)
EndFunc   ;==>_IniReadToArrayFromString

; ###############################################################################################################################

; ===============================================
; = Internal Use Only
; ===============================================
Func __StringEscapeRegExp($szExp)
    Return StringRegExpReplace($szExp, "([\(\)\[\]\{\}\\\/\?\.\\|\+])", "\\$1") ; ()[]{}\/?.|+
EndFunc   ;==>__StringEscapeRegExp

Example:

; #INDEX# =======================================================================================================================
; Title .........: IniEx_example
; Date ..........: 06.02.2011
; AutoIt Version : 3.3 + (development version = 3.3.6.0)
; Language ......: English
; Description ...: Examples for IniEx UDF
; Requires ......: IniEx.au3
; Remarks .......:
; Link ..........: http://www.autoitscript.com/forum/topic/125163-iniex-udf/
; Author ........: FichteFoll
; ===============================================================================================================================

#AutoIt3Wrapper_AU3Check_Parameters=-d -w 3 -w 4 -w 5 -w 6

#include <IniEx.au3>

_Example()

Func _Example()
    Local $szIniString, $aszSectionnames, $aszSection, $aszIniContent, $aszIniReadContent, $szIniPath = @TempDir & "\file.ini"

    ; generate ini string
    For $i = 1 To 15
        $szIniString &= StringFormat("[section%02d]\n", $i)
        $szIniString &= StringFormat("key%02d,0=%s%s\n", $i, ChrW(30693), ChrW(35782)) ; 知识

        For $j = 1 To 15
            $szIniString &= StringFormat("key%02d,%d=value%02d\n", $i, $j, $j)
        Next
    Next
    $szIniString = StringAddCR($szIniString)
    MsgBox(0, "$szIniString", StringLeft($szIniString, 284)) ; see Unicode in key 0

    ; section-functions
    $aszSectionnames = _IniReadSectionNamesFromString($szIniString)
    ConsoleWrite("! _IniReadSectionNamesFromString($szIniString) : " & @CRLF)
    _ArrayPrint($aszSectionnames)

    $aszSection = _IniReadSectionFromString($szIniString, $aszSectionnames[$aszSectionnames[0]])
    ConsoleWrite("! _IniReadSectionFromString($szIniString, $aszSectionnames[$aszSectionnames[0]]) : " & @CRLF)
    _ArrayPrint($aszSection)


    ; array-functions
    $aszIniContent =_IniReadToArrayFromString($szIniString)
    _IniWriteFromArray($szIniPath, $aszIniContent)
    If @error Then Exit 1
    $aszIniReadContent = _IniReadToArray($szIniPath)
    _ShowIniArray($aszIniReadContent, 10) ; No Unicode displayed in key00

    _IniWriteFromArray($szIniPath, $aszIniContent, True) ; using _IniConvertToUnicode
    If @error Then Exit 2
    $aszIniReadContent = _IniReadToArray($szIniPath)
    _ShowIniArray($aszIniReadContent, 10) ; Unicode recogniced in key00
EndFunc

#include <Array.au3>

Func _ShowIniArray(Const ByRef $aArray, $iIndex = -1)

    Local $step = $aArray[0][0][0]
    If $iIndex = -1 Then
        $step = 1
        $iIndex = 1
    EndIf

    ; Console does not support Unicode, using _ArrayDisplay instead
    For $i = $iIndex To $aArray[0][0][0] Step $step
        Local $aszSection[1][2] = [[$aArray[$i][0][0], $aArray[$i][0][1]]]

        For $j = 1 To UBound($aArray, 2) - 1
            If $aArray[$i][$j][0] = "" And $aArray[$i][$j][1] = "" Then ExitLoop ; empty entry
            ReDim $aszSection[$j+1][2]
            $aszSection[$j][0] = $aArray[$i][$j][0]
            $aszSection[$j][1] = $aArray[$i][$j][1]
        Next
        _ArrayDisplay($aszSection)
    Next

;~  For $i = 1 To $aszIniReadContent[0][0][0] Step $step
;~      ConsoleWrite(StringFormat("! [%s]", $aszIniReadContent[$i][0][0]) & @CRLF)
;~      For $j = 1 To $aszIniReadContent[$i][0][1]
;~          ConsoleWrite(StringFormat("- %s=%s", $aszIniReadContent[$i][$j][0], $aszIniReadContent[$i][$j][1]) & @CRLF)
;~      Next
;~  Next
EndFunc


; #Function# ===========================================================================================================================================
; Name............: _ArrayPrint
; Description.....: Prints a one or two dimensional array as a table into the console or just returns the table as string
; Syntax..........: _ArrayPrint(Const ByRef $aArray, $bConsole = True, $nLine = @ScriptLineNumber)
; Parameters......:
;       Const ByRef $aArray      - The Array to print; with one or two dimensions
;                   $bConsole    - [optional] If False the table will not be printed to the console and only returned
;                   $nLine       - [optional] Contains the script line number and will be printed on top of the SciTE-Console
;                                             (requires uncompiled script and $bConsole = True)
; Return values...:
;                   Success      - The table as string
;                   Failure      - Returns 0 - sets @error
;                                              1 - $aArray is not an array
;                                              2 - $aArray has more than two dimensions
; Author .........: FichteFoll
; Remarks ........: The output for $bConsole will be different if the Script is compiled or not and uses SciTE's cosole highlighting
; Related ........: _ArrayDisplay
; Requires .......: __Max (or _Max from Math.au3)
; Link ...........;
; Example ........; _ArrayPrint(WinList())
; ======================================================================================================================================================
Func _ArrayPrint(Const ByRef $aArray, $bConsole = True, $nLine = @ScriptLineNumber)
    If Not IsArray($aArray) Then Return SetError(1)
    Local $sExec, $sLine = '', $sOutput = ''

    Switch UBound($aArray, 0)
        Case 1
            Local $aiLenMax[2] = [__Max(StringLen(String(UBound($aArray, 1) - 1)), 3), 0], _
                    $acFlag[2] = ['', ''] ; "Row" = 3

            For $i = 0 To UBound($aArray, 1) - 1
                $aiLenMax[1] = __Max(StringLen(String($aArray[$i])), $aiLenMax[1])
                If IsString($aArray[$i]) Then $acFlag[1] = '-'
            Next

            ; Arrayheader
            If $bConsole Then
                $sLine = StringFormat("--- Array[%d] ---", UBound($aArray))
                $sOutput = $sLine & @CRLF
                If Not @Compiled Then $sLine = StringFormat("@@ Debug(%d) : Array[%d]", $nLine, UBound($aArray))
                ConsoleWrite($sLine & @CRLF)
            EndIf

            ; Header
            $sLine = StringFormat('+ %' & $acFlag[0] & $aiLenMax[0] & 's + %' & $acFlag[1] & $aiLenMax[1] & 's +', 'Row', 'Content')

            $sOutput &= $sLine
            If Not @Compiled Then $sLine = '- ' & $sLine
            If $bConsole Then ConsoleWrite($sLine & @CRLF)

            ; Lines
            For $i = 0 To UBound($aArray, 1) - 1
                $sLine = StringFormat('| %' & $acFlag[0] & $aiLenMax[0] & 'd | %' & $acFlag[1] & $aiLenMax[1] & 's |', $i, StringReplace(String($aArray[$i]), "'", "\'"))

                $sOutput &= @CRLF & $sLine
                If Not @Compiled Then $sLine = '> ' & $sLine
                If $bConsole Then ConsoleWrite($sLine & @CRLF)
            Next

            ; Footer
            $sLine = '+'
            For $i = 0 To 1
                $sLine &= '-'
                For $j = 1 To $aiLenMax[$i]
                    $sLine &= '-'
                Next
                $sLine &= '-+'
            Next

            $sOutput &= @CRLF & $sLine
            If Not @Compiled Then $sLine = '- ' & $sLine
            If $bConsole Then ConsoleWrite($sLine & @CRLF)

            Return $sOutput

        Case 2
            Local $aiElmts[2] = [UBound($aArray, 1), UBound($aArray, 2)], _
                    $aiLenMax[$aiElmts[1] + 1], _
                    $acFlag[$aiElmts[1] + 1]
            $aiLenMax[0] = __Max(StringLen(String(UBound($aArray, 1) - 1)), 3) ; "Row" = 3
            $acFlag[0] = '-'

            For $j = 0 To $aiElmts[1] - 1
                $aiLenMax[$j + 1] = StringLen(String(UBound($aArray, 2) - 1)) + 4 ; "Col_" = 4
            Next
            For $i = 0 To $aiElmts[0] - 1
                For $j = 0 To $aiElmts[1] - 1
                    $aiLenMax[$j + 1] = __Max(StringLen(String($aArray[$i][$j])), $aiLenMax[$j + 1])
                    If IsString($aArray[$i][$j]) Then $acFlag[$j + 1] = '-'
                Next
            Next

            ; Arrayheader
            If $bConsole Then
                $sLine = StringFormat("--- Array[%d] ---", UBound($aArray))
                $sOutput = $sLine & @CRLF
                If Not @Compiled Then $sLine = StringFormat("@@ Debug(%d) : Array[%d][%d]", $nLine, UBound($aArray, 1), UBound($aArray, 2))
                ConsoleWrite($sLine & @CRLF)
            EndIf

            ; Header
            $sExec = "StringFormat('+ %" & $acFlag[0] & $aiLenMax[0] & "s"
            For $j = 0 To $aiElmts[1] - 1
                $sExec &= " + %" & $acFlag[$j + 1] & $aiLenMax[$j + 1] & "s"
            Next
            $sExec &= " +', 'Row'"
            For $j = 0 To $aiElmts[1] - 1
                $sExec &= ", 'Col_" & $j & "'"
            Next
            $sExec &= ")"
            $sLine = Execute($sExec)

            $sOutput &= $sLine
            If Not @Compiled Then $sLine = '- ' & $sLine
            If $bConsole Then ConsoleWrite($sLine & @CRLF)

            ; Lines
            For $i = 0 To $aiElmts[0] - 1
                $sExec = "StringFormat('| %" & $aiLenMax[0] & "d"
                For $j = 0 To $aiElmts[1] - 1
                    $sExec &= " | %" & $acFlag[$j + 1] & $aiLenMax[$j + 1] & "s"
                Next
                $sExec &= " |', " & $i
                For $j = 0 To $aiElmts[1] - 1
                    $sExec &= ", '" & StringReplace(String($aArray[$i][$j]), "'", "\'") & "'"
                Next
                $sExec &= ")"
                $sLine = Execute($sExec)

                $sOutput &= @CRLF & $sLine
                If Not @Compiled Then $sLine = '> ' & $sLine
                If $bConsole Then ConsoleWrite($sLine & @CRLF)
            Next

            ; Footer
            $sLine = '+'
            For $i = 0 To $aiElmts[1]
                $sLine &= '-'
                For $j = 1 To $aiLenMax[$i]
                    $sLine &= '-'
                Next
                $sLine &= '-+'
            Next

            $sOutput &= @CRLF & $sLine
            If Not @Compiled Then $sLine = '- ' & $sLine
            If $bConsole Then ConsoleWrite($sLine & @CRLF)

            Return $sOutput
        Case Else

    EndSwitch

    Return -2
EndFunc   ;==>_ArrayPrint

Func __Max($nNum1, $nNum2)
    If $nNum1 > $nNum2 Then Return $nNum1
    Return $nNum2
EndFunc   ;==>__Max

By the way I had some problems using RegExp for _IniReadSectionFromString using StringRegExp($szInput, "(?<=\n|\A)\[" & __StringEscapeRegExp($szSection) & "\](?:\n+?(.*?)=(.*))+(?=\n?\Z|\n\[)", 1) where only the last key of the section is returned. I totally don't understand how all the lines between the section header and the last key get ignored since I used "+" but maybe one of you could help me with that. I'm parsing the string line by line as a workaround at the moment bur I left the RegExp-Part as comment inside.

Please let me know if you found bugs or improvements.

Edited by FichteFoll
Link to comment
Share on other sites

Related:

 

Spoiler

Using OS: Win 7 Professional, Using AutoIt Ver(s): 3.3.6.1 / 3.3.8.1

AutoIt_Rus_Community.png AutoIt Russian Community

My Work...

Spoiler

AutoIt_Icon_small.pngProjects: ATT - Application Translate Tool {new}| BlockIt - Block files & folders {new}| SIP - Selected Image Preview {new}| SISCABMAN - SciTE Abbreviations Manager {new}| AutoIt Path Switcher | AutoIt Menu for Opera! | YouTube Download Center! | Desktop Icons Restorator | Math Tasks | KeyBoard & Mouse Cleaner | CaptureIt - Capture Images Utility | CheckFileSize Program

AutoIt_Icon_small.pngUDFs: OnAutoItErrorRegister - Handle AutoIt critical errors {new}| AutoIt Syntax Highlight {new}| Opera Library! | Winamp Library | GetFolderToMenu | Custom_InputBox()! | _FileRun UDF | _CheckInput() UDF | _GUIInputSetOnlyNumbers() UDF | _FileGetValidName() UDF | _GUICtrlCreateRadioCBox UDF | _GuiCreateGrid() | _PathSplitByRegExp() | _GUICtrlListView_MoveItems - UDF | GUICtrlSetOnHover_UDF! | _ControlTab UDF! | _MouseSetOnEvent() UDF! | _ProcessListEx - UDF | GUICtrl_SetResizing - UDF! | Mod. for _IniString UDFs | _StringStripChars UDF | _ColorIsDarkShade UDF | _ColorConvertValue UDF | _GUICtrlTab_CoverBackground | CUI_App_UDF | _IncludeScripts UDF | _AutoIt3ExecuteCode | _DragList UDF | Mod. for _ListView_Progress | _ListView_SysLink | _GenerateRandomNumbers | _BlockInputEx | _IsPressedEx | OnAutoItExit Handler | _GUICtrlCreateTFLabel UDF | WinControlSetEvent UDF | Mod. for _DirGetSizeEx UDF
 
AutoIt_Icon_small.pngExamples: 
ScreenSaver Demo - Matrix included | Gui Drag Without pause the script | _WinAttach()! | Turn Off/On Monitor | ComboBox Handler Example | Mod. for "Thinking Box" | Cool "About" Box | TasksBar Imitation Demo

Like the Projects/UDFs/Examples? Please rate the topic (up-right corner of the post header: Rating AutoIt_Rating.gif)

* === My topics === *

==================================================
My_Userbar.gif
==================================================

 

 

 

AutoIt is simple, subtle, elegant. © AutoIt Team

Link to comment
Share on other sites

Didn't see that, but I guess since I provide some extra functions that is going to be ok.

I'm now experimenting with "(?ix) (?<=\[" & __StringEscapeRegExp($szSection) & "\](?:\r\n)+? (?=(?:.*?=.*(?:\r\n)+?)*?) ) (?P<Key>.*?)=(?P<Value>.*)" but that does only return the first line instead of parsing all possibilities (which means all key=section lines afterwards because of the "(?=(?:.*?=.*(?:\r\n)+?)*?)" ...

And I cannot edit my first post, it should be possible for me to do so even after some hours. I already saw people editing their posts about a year after initially posting it. Is there a limit only for new registered users?

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...