Jump to content

"ini" file creation with default options and strings of text


Recommended Posts

Hi all,

I figured out how to, in the case of a missing .ini configuration file, create a new file (section by section, with the use of "IniWriteSection" associated to arrays with the options to be get), but i cannot see how to write efficiently in the ini file comments.

i.e., if i have a couple of sections i can write:

If $iniexist==0 Then

MsgBox(0, "Notice", "No .ini found. Default options loaded and .ini file is going to be created.", 5)

Local $sect1 [4][2] = [["var1_1", 1], ["var1_2", 2], ["var1_3", 3], ["var1_4", 4]]
Local $sect2 [3][2] = [["var2_1", 5], ["var2_2", 6], ["var2_3", 7]]

IniWriteSection($file_ini, "section_1", $sect1, 0)
IniWriteSection($file_ini, "section_2", $sect2, 0)

EndIf

and i will end up with

[section_1]
var1_1=1
var1_2=2
var1_3=3
var1_4=4

[section_2]
var2_1=5
var2_2=6
var2_3=7

but if i have a bunch of text in the middle i want to be reported, like:

[section_1]
var1_1=1
var1_2=2
var1_3=3
var1_4=4

;Inferno: Canto I

;Midway upon the journey of our life
; I found myself within a forest dark,
;For the straightforward pathway had been lost.
;Ah me! how hard a thing it is to say
; What was this forest savage, rough, and stern,
; Which in the very thought renews the fear.
;So bitter is it, death is little more;
; But of the good to treat, which there I found,
; Speak will I of the other things I saw there.
;I cannot well repeat how there I entered,
; So full was I of slumber at the moment
; In which I had abandoned the true way.
;But after I had reached a mountain's foot,
; At that point where the valley terminated,
; Which had with consternation pierced my heart,
;Upward I looked, and I beheld its shoulders,
; Vested already with that planet's rays
; Which leadeth others right by every road.
;Then was the fear a little quieted
; That in my heart's lake had endured throughout
; The night, which I had passed so piteously.
;And even as he, who, with distressful breath,
; Forth issued from the sea upon the shore,
; Turns to the water perilous and gazes;
;So did my soul, that still was fleeing onward,
; Turn itself back to re-behold the pass
; Which never yet a living person left.

[section_2]
var2_1=5
var2_2=6
var2_3=7

;After my weary body I had rested,
; The way resumed I on the desert slope,
; So that the firm foot ever was the lower.
;And lo! almost where the ascent began,
; A panther light and swift exceedingly,
; Which with a spotted skin was covered o'er!
;And never moved she from before my face,
; Nay, rather did impede so much my way,
; That many times I to return had turned.
;The time was the beginning of the morning,
; And up the sun was mounting with those stars
; That with him were, what time the Love Divine
;At first in motion set those beauteous things;
; So were to me occasion of good hope,
; The variegated skin of that wild beast,
;The hour of time, and the delicious season;
; But not so much, that did not give me fear
; A lion's aspect which appeared to me.

How can i create efficiently a full .ini file with all the sections, variables and text?

Thanks :)

Edited by Baritonomarchetto
Link to comment
Share on other sites

Unfortunately, the native INI functions don't support comments in the ini files, you can't write them using them, and they're ignored (like they should be) when reading the ini files.

If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.
Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag Gude
How to ask questions the smart way!

I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from.

Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays.  -  ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script.  -  Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label.  -  _FileGetProperty - Retrieve the properties of a file  -  SciTE Toolbar - A toolbar demo for use with the SciTE editor  -  GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI.  -   Latin Square password generator

Link to comment
Share on other sites

If all you're doing is building a new ini file... you should be able to create section_1 and its variables, then FileOpen(), FileWrite() appending your comments, FileClose(). Then create section_2 and its variables etc.

Spoiler

“Hello, ladies, look at your man, now back to me, now back at your man, now back to me. Sadly, he isn’t me, but if he stopped using ladies scented body wash and switched to Old Spice, he could smell like he’s me. Look down, back up, where are you? You’re on a boat with the man your man could smell like. What’s in your hand, back at me. I have it, it’s an oyster with two tickets to that thing you love. Look again, the tickets are now diamonds. Anything is possible when your man smells like Old Spice and not a lady. I’m on a horse.”

 

Link to comment
Share on other sites

I remembered a topic that came up about this a year ago. In that thread the same question was asked and I spent a little time in coming up with a that will add comments to an INI file. Take a look at the script as it seems to do what you're looking for.

EDIT: Just discovered a bug in that script I linked to, see below:

NVM, the bug wasn't a bug, just me misreading what I put in there a year ago. :oops: No change necessary to the script in the linked post.

Edited by BrewManNH

If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.
Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag Gude
How to ask questions the smart way!

I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from.

Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays.  -  ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script.  -  Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label.  -  _FileGetProperty - Retrieve the properties of a file  -  SciTE Toolbar - A toolbar demo for use with the SciTE editor  -  GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI.  -   Latin Square password generator

Link to comment
Share on other sites

I have updated the code that I posted in that thread from a year ago, there were a few errors in it, and I also created a new function called _IniStripComments which will strip the comments out of your INI file, you could use this to change comments in your INI file by stripping out the old ones and replacing them with the new ones.

#include-once
#include <File.au3>
#include <array.au3>
;Test function to write comments to an ini file
Global $IniFile = @ScriptDir & "Test.ini"
FileOpen($IniFile, 2)
IniWrite($IniFile, "Test1", 1, 1)
IniWrite($IniFile, "Test1", 2, 2)
IniWrite($IniFile, "Test1", 3, 3)
IniWrite($IniFile, "Test1", 4, 4)
IniWrite($IniFile, "Test2", 1, 1)
IniWrite($IniFile, "Test2", 2, 2)
IniWrite($IniFile, "Test2", 3, 3)
IniWrite($IniFile, "Test3", 1, 1)
IniWrite($IniFile, "Test3", 2, 2)
IniWrite($IniFile, "Test3", 3, 3)
Global $Test = _IniWriteSectionComment($IniFile, "Test1", "This is a comment that comes before a section name", 1)
$Test = _IniWriteSectionComment($IniFile, "Test2", "This is a comment that comes after a section name", 0)
$Test = _IniWriteSectionComment($IniFile, "Test3", "This is a multi-line comment|that comes after a section name", 0)
$Test = _IniWriteSectionComment($IniFile, "Test4", "This will cause an error by referencing a non-existent section name", 0)
ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $Test = ' & $Test & @crlf & '>Error code: ' & @error & @crlf) ;### Debug Console
$Test = _IniWriteSectionComment($IniFile, "Test3", "This is a NEW multi-line comment|that comes after a section name", 0)
$Test = _IniWriteSectionComment($IniFile, "Test3", "This is a multi-line comment|that comes before a section name", 1)
;~ $Test = _IniStripComments($IniFile, 0, "Test3", 1) ; This will strip the comments from before the section Test3
; #FUNCTION# ====================================================================================================================
; Name...........: _IniWriteSectionComment
; Description ...: Writes comment(s) to an .ini file
; Syntax.........: _IniWriteSectionComment($IWSC_FileName, $IWSC_SectionName, $IWSC_Comment[, $IWSC_ForeAft = 1])
; Parameters ....: $IWSC_FileName      - String path of the file to write to.
;                 $IWSC_SectionName    - The section of the ini file to comment.
;                 $IWSC_Comment     - String that contains the comment for the section name.
;                 $IWSC_ForeAft     - Optional: Specifies where to put the comment in relation to the section name
;                                        default is before the section name.
; Return values .: Success - Returns a 1
;                 Failure - Returns a 0
;                 @Error  - 0 = No error.
;                 |1 = file not found
;                 |2 = Could not read/split file
;                 |3 = Not an .ini file
;                 |4 = Section Name not found
; Author ........: Bob Marotte (BrewManNH)
; Modified.......:
; Remarks .......: $IWSC_ForeAft specifies whether to put the comments before or after the section name, 1 = before/0 = after
;                 To write multiline comments, separate the lines with the "|" (pipe) character, see example below.
; Related .......:
; Link ..........:
; Example .......: $Test = _IniWriteSectionComment($IniFile, "Settings", "Now is the time for all good|men to come to the aid of their country", 1)
; ===============================================================================================================================
Func _IniWriteSectionComment($IWSC_FileName, $IWSC_SectionName, $IWSC_Comment, $IWSC_ForeAft = 1)
 Local $aFileRead
 If FileExists($IWSC_FileName) Then
  Local $IWSC_fHnd = FileOpen($IWSC_FileName, 0)
  If $IWSC_fHnd = -1 Then
   Return SetError(2, 0, 0)
  EndIf
  Local $Return = _FileReadToArray($IWSC_FileName, $aFileRead)
  If $Return = 0 Then
   Return SetError(2, 0, 0)
  EndIf
  Local $aSectionNames = IniReadSectionNames($IWSC_FileName)
  If @error Then
   Return SetError(3, 0, 0)
  EndIf
  If _ArraySearch($aSectionNames, $IWSC_SectionName) < 0 Then
   Return SetError(4, 0, 0)
  EndIf
  Local $aTempArray = StringSplit($IWSC_Comment, "|")
  Local $IWSC_Index = _ArraySearch($aFileRead, "[" & $IWSC_SectionName & "]")
  Local $aHolder[UBound($aFileRead) + UBound($aTempArray) - 1]
  If $IWSC_ForeAft Then
   For $I = 0 To $IWSC_Index - 1
    $aHolder[$I] = $aFileRead[$I]
   Next
   For $I = $IWSC_Index To $aTempArray[0] + $IWSC_Index - 1
    $aHolder[$I] = "; " & $aTempArray[$I - ($IWSC_Index - 1)]
   Next
   For $I = $IWSC_Index To $aFileRead[0]
    $aHolder[$I + $aTempArray[0]] = $aFileRead[$I]
   Next
  Else
   For $I = 0 To $IWSC_Index
    $aHolder[$I] = $aFileRead[$I]
   Next
   For $I = $IWSC_Index + 1 To $aTempArray[0] + $IWSC_Index
    $aHolder[$I] = "; " & $aTempArray[$I - ($IWSC_Index)]
   Next
   For $I = $IWSC_Index + 1 To $aFileRead[0]
    $aHolder[$I + $aTempArray[0]] = $aFileRead[$I]
   Next
  EndIf
  _ArrayDelete($aHolder, 0)
  _FileWriteFromArray($IWSC_FileName, $aHolder)
 Else
  Return SetError(1, 0, 0)
 EndIf
 Return SetError(0, 0, 1)
EndFunc   ;==>_IniWriteSectionComment
; #FUNCTION# ====================================================================================================================
; Name...........: _IniStripComments
; Description ...: Strips comment(s) from an .ini file
; Syntax.........: _IniStripComments($ISC_FileName[, $ISC_All = 1[, $ISC_SectionName=""[, $ISC_ForeAft = 1]]])
; Parameters ....: $ISC_FileName        - String path of the file to work with
;                 $ISC_All           - Strip all comments in the ini file (default is yes)
;                 $ISC_SectionName   - The section of the ini file to strip comments from, can not be left blank.
;                 $ISC_ForeAft       - Optional: Specifies where to strip the comments in relation to the section name
;                                        default is before the section name.
; Return values .: Success - Returns a 1
;                 Failure - Returns a 0
;                 @Error  - 0 = No error.
;                 |1 = file not found
;                 |2 = Could not read/split file
;                 |3 = Not an .ini file
;                 |4 = Section Name not found or not specified
; Author ........: Bob Marotte (BrewManNH)
; Modified.......:
; Remarks .......: $ISC_ForeAft specifies whether to strip the comments before or after the section name, 1 = before/0 = after
;                 If you use the $ISC_All = 1 option, then the other parameters after it are ignored.
; Related .......:
; Link ..........:
; Example .......: $Test = _IniWriteSectionComment($IniFile, "Settings", "Now is the time for all good|men to come to the aid of their country", 1)
; ===============================================================================================================================
Func _IniStripComments($ISC_FileName, $ISC_All = 1, $ISC_SectionName="", $ISC_ForeAft = 1)
 Local $aFileRead
 If FileExists($ISC_FileName) Then
  Local $ISC_fHnd = FileOpen($ISC_FileName, 0)
  If $ISC_fHnd = -1 Then
   Return SetError(2, 0, 0)
  EndIf
  Local $Return = _FileReadToArray($ISC_FileName, $aFileRead)
  If $Return = 0 Then
   Return SetError(2, 0, 0)
  EndIf
  Local $aSectionNames = IniReadSectionNames($ISC_FileName)
  If @error Then
   Return SetError(3, 0, 0)
  EndIf
  If $ISC_All = 1 Then
   For $I = $aFileRead[0] To 1 Step -1
    If StringLeft($aFileRead[$I], 1) = ";" Then
     _ArrayDelete($aFileRead, $I)
    EndIf
   Next
   _ArrayDelete($aFileRead, 0)
   _FileWriteFromArray($ISC_FileName, $aFileRead)
   Return 1
  EndIf
  If _ArraySearch($aSectionNames, $ISC_SectionName) < 0 Or $ISC_SectionName = "" Then
   Return SetError(4, 0, 0)
  EndIf
  Local $aSectionNames = IniReadSectionNames($ISC_FileName)
  If @error Then
   Return SetError(3, 0, 0)
  EndIf
  If _ArraySearch($aSectionNames, $ISC_SectionName) < 0 Then
   Return SetError(4, 0, 0)
  EndIf
  Local $ISC_Index = _ArraySearch($aFileRead, "[" & $ISC_SectionName & "]")
  Local $aHolder[$aFileRead[0] + 1]
  If $ISC_ForeAft Then
   For $I = 0 To $ISC_Index - 1
    $aHolder[$I] = $aFileRead[$I]
   Next
   For $I = $ISC_Index - 1 To 0 Step -1
    If StringLeft($aHolder[$I], 1) = ";" Then
     _ArrayDelete($aHolder, $I)
     _ArrayDelete($aFileRead, $I)
     $aFileRead[0] = $aFileRead[0] - 1
     $ISC_Index -= 1
    Else
     ExitLoop
    EndIf
   Next
   For $I = $ISC_Index To $aFileRead[0]
    $aHolder[$I] = $aFileRead[$I]
   Next
  Else
   Local $tmpIndex = $ISC_Index
   For $I = 0 To $ISC_Index
    $aHolder[$I] = $aFileRead[$I]
   Next
   For $I = $ISC_Index + 1 To $aFileRead[0]
    If StringLeft($aFileRead[$I], 1) = ";" Then
     $ISC_Index += 1
    Else
     ExitLoop
    EndIf
   Next
   For $I = $ISC_Index + 1 To $aFileRead[0]
    $aHolder[$I] = $aFileRead[$I]
   Next
   For $I = $aFileRead[0] To $tmpIndex Step -1
    If $aHolder[$I] = "" Then
     _ArrayDelete($aHolder, $I)
    EndIf
   Next
  EndIf
  _ArrayDelete($aHolder, 0)
  _FileWriteFromArray($ISC_FileName, $aHolder)
 Else
  Return SetError(1, 0, 0)
 EndIf
 Return SetError(0, 0, 1)
EndFunc   ;==>_IniStripComment

I'll also be posting this in the Snippets thread if anyone is interested. :)

If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.
Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag Gude
How to ask questions the smart way!

I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from.

Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays.  -  ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script.  -  Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label.  -  _FileGetProperty - Retrieve the properties of a file  -  SciTE Toolbar - A toolbar demo for use with the SciTE editor  -  GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI.  -   Latin Square password generator

Link to comment
Share on other sites

Baritonomarchetto

$sPathIni = @ScriptDir & 'Set.ini'
If Not FileExists($sPathIni) Then
    _IniDef($sPathIni)
EndIf

IniWrite($sPathIni, 'section_2', 'var2_2', '12345')
MsgBox(0, 'Сообщение', IniRead($sPathIni, 'section_2', 'var2_2', 'NotFound'))

Func _IniDef($sPathIni)
    $hFile = FileOpen($sPathIni, 2)
    FileWrite($hFile, _
            '[section_1]' & @CRLF & _
            'var1_1=1' & @CRLF & _
            'var1_2=2' & @CRLF & _
            'var1_3=3' & @CRLF & _
            'var1_4=4' & @CRLF & _
            @CRLF & _
            ';Inferno: Canto I' & @CRLF & _
            @CRLF & _
            ';Midway upon the journey of our life' & @CRLF & _
            '; I found myself within a forest dark,' & @CRLF & _
            ';For the straightforward pathway had been lost.' & @CRLF & _
            ';Ah me! how hard a thing it is to say' & @CRLF & _
            '; What was this forest savage, rough, and stern,' & @CRLF & _
            '; Which in the very thought renews the fear.' & @CRLF & _
            ';So bitter is it, death is little more;' & @CRLF & _
            '; But of the good to treat, which there I found,' & @CRLF & _
            '; Speak will I of the other things I saw there.' & @CRLF & _
            ';I cannot well repeat how there I entered,' & @CRLF & _
            '; So full was I of slumber at the moment' & @CRLF & _
            '; In which I had abandoned the true way.' & @CRLF & _
            ';But after I had reached a mountain''s foot,' & @CRLF & _
            '; At that point where the valley terminated,' & @CRLF & _
            '; Which had with consternation pierced my heart,' & @CRLF & _
            ';Upward I looked, and I beheld its shoulders,' & @CRLF & _
            '; Vested already with that planet''s rays' & @CRLF & _
            '; Which leadeth others right by every road.' & @CRLF & _
            ';Then was the fear a little quieted' & @CRLF & _
            '; That in my heart''s lake had endured throughout' & @CRLF & _
            '; The night, which I had passed so piteously.' & @CRLF & _
            ';And even as he, who, with distressful breath,' & @CRLF & _
            '; Forth issued from the sea upon the shore,' & @CRLF & _
            '; Turns to the water perilous and gazes;' & @CRLF & _
            ';So did my soul, that still was fleeing onward,' & @CRLF & _
            '; Turn itself back to re-behold the pass' & @CRLF & _
            '; Which never yet a living person left.' & @CRLF & _
            @CRLF & _
            '[section_2]' & @CRLF & _
            'var2_1=5' & @CRLF & _
            'var2_2=6' & @CRLF & _
            'var2_3=7' & @CRLF & _
            @CRLF & _
            ';After my weary body I had rested,' & @CRLF & _
            '; The way resumed I on the desert slope,' & @CRLF & _
            '; So that the firm foot ever was the lower.' & @CRLF & _
            ';And lo! almost where the ascent began,' & @CRLF & _
            '; A panther light and swift exceedingly,' & @CRLF & _
            '; Which with a spotted skin was covered o''er!' & @CRLF & _
            ';And never moved she from before my face,' & @CRLF & _
            '; Nay, rather did impede so much my way,' & @CRLF & _
            '; That many times I to return had turned.' & @CRLF & _
            ';The time was the beginning of the morning,' & @CRLF & _
            '; And up the sun was mounting with those stars' & @CRLF & _
            '; That with him were, what time the Love Divine' & @CRLF & _
            ';At first in motion set those beauteous things;' & @CRLF & _
            '; So were to me occasion of good hope,' & @CRLF & _
            '; The variegated skin of that wild beast,' & @CRLF & _
            ';The hour of time, and the delicious season;' & @CRLF & _
            '; But not so much, that did not give me fear' & @CRLF & _
            '; A lion''s aspect which appeared to me.')
    FileClose($hFile)
EndFunc

Link to comment
Share on other sites

Thank you all!

Following the example of AZJIO i had an "error parsing function call" for a script like:

Global $file_ini = @ScriptDir & "inifile.ini"
Local $iniexist = FileExists($file_ini)

If Not $iniexist Then
MsgBox(0, "Notice", "No .ini found. Default options loaded and .ini file is going to be created.", 5)
IniWrite($file_ini, "", "", "") ;create an empty file
_inidef($file_ini)
EndIf

Func _inidef($file_ini)
$hFile = FileOpen($file_ini, 2)
FileWrite($hFile, _
"[section_1]" & @CRLF & _
"var1 = 1" & @CRLF & _
@CRLF)
FileClose($hFile)
EndFunc

what is wrong with it?

Thanks!

Edited by Baritonomarchetto
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...