Tcl/TK -- How to read a ini file

ini file example:

[database]
dbsrc = db
dbusr = sa
dbpwd = 1234

 invoke example:

ReadIni $ini "database"
if {[info exists iniAttribute(dbsrc)]} {
	set dbsrc $iniAttribute(dbsrc)
}

 source code:

set iniLocation "$env(windir)\\oms.ini"
array set iniAttribute ""

proc ReadIni {section} {

	global iniAttribute 
	global iniLocation
	global env

	set location "oms.ini"
  
	if { [catch { open $location r } iniSource] } {
		set location $iniLocation
		if { [catch { open $location r } iniSource] } {
			puts stderr "Could not open $location for reading\n"
			return
		}
	}
	while { [eof $iniSource] == 0} {
		
		gets $iniSource line
		if {![regexp {^ *\[.+\] *$} $line ]} {
			continue
		}
		# At this point, the line contain the section
		regsub " +$" $line {} line
		regsub "^ +" $line {} line
		if { $line == "\[$section\]" } {
			
			while { [eof $iniSource] == 0} {
				
				gets $iniSource line
				regsub " +$" $line {} line
				regsub "^ +" $line {} line
				
				if {![regexp {\[.+\]} $line]} {
					
					if {[regexp {.*=.*} $line]} {
						
						set pair [split $line "="]
						set len [llength $pair]
						
						regsub " +$" [lindex $pair 0] {} attr
						
						if {$len >2} {
							set value [lindex $pair 1]
							for {set i 2} {$i<$len} {incr i} {
								append value " = [lindex $pair $i]" 
							}
						
						} else {
							regsub "^ +" [lindex $pair 1] {} value
						}						
						
						set ss [string first "%" $value]
						set ee [string last "%" $value]
						
						if { $ss >= 0 && $ee > $ss} {
						set ss [expr $ss + 1]
						set ee [expr $ee - 1]
						set evar [string range $value $ss $ee]
					
						if { [regsub "%\[0-9a-zA-Z\]+%" $value $env($evar) var2] > 0 } {
								set value $var2
							}
						}
						
						regsub " +$" $value {} value
						set iniAttribute($attr) $value
					}
				
				} else {
					break
				}
			}
		}
	}
	
	close $iniSource
}


 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值