0

Is it possible to read an ini file in reverse?

Can it be done with a "sort" or a "filereadline" loop?

a.ini

[section1]
key1=1
[section2]
key2=2
[section3]
key3=3
[section4]
key4=4

Code:

FileRead, file, a.ini
Gui, Font, s14 cBlue
Gui Add, Edit, w435 h400 vfile, %file%
Gui, show

the result i want:

[section4]
key4=4
[section3]
key3=3
[section2]
key2=2
[section1]
key1=1

2 Answers 2

1
; Read in a list of the section names
IniRead,sectionsString,a.ini

; Split the list into an array
; The 0th term will contain the count of how many items there are in the array
StringSplit,sectionsArray,sectionsString,`n

; Read each section in reverse order and compile the results
reversedIni=
Loop, %sectionsArray0%
{
    ; We want to count from end of the list to the beginning so adjust based on A_Index
    thisSectionNumber := sectionsArray0 - A_Index + 1
    
    ; Pull the name of this section
    thisSection := sectionsArray%thisSectionNumber%
    
    ; Read the text from this section
    IniRead,sectionText,a.ini,%thisSection%
    
    ; Format the results and add it to the reversed INI we're building
    reversedIni := reversedIni . "[" . thisSection . "]`n" . sectionText . "`n"
}

; Display the result
Msgbox % reversedIni

enter image description here

1
  • thank you so much i've been working on this for a long time... and thank you so much for the code comment lines
    – emreya
    Commented Jan 24, 2022 at 19:21
1
Loop, read, a.ini  ; retrieves the lines in this file, one at a time
{
    If (SubStr(A_LoopReadLine, 1, 1) = "[") ; section
        content .= "`n" A_LoopReadLine ; concatenate the outputs by adding a linefeed before each one
    else ; key
        content .= A_Space A_LoopReadLine ; concatenate the outputs by adding a space before each one
}
; MsgBox, %content%
Sort, content, R ; sort the concatenated lines in reverse order
; MsgBox, %content%
Loop, parse, content, `n ; split by linefeed
{
    If (A_LoopField = "") ; ignore empty lines
       continue
    LoopField := StrReplace(A_LoopField, A_Space, "`n") ; replace spaces by linefeeds
    result .= "`n" LoopField ; concatenate the outputs
}
result := Trim(result, "`n") ; remove leading linefeeds 
MsgBox, %result%
1
  • this works thank you very much also for the comment lines
    – emreya
    Commented Jan 24, 2022 at 19:23

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .