Loading and Saving Application Configuration Files

WJG (12/Feb/06) The value of using Tcl/Tk to write to create handy utilities can never be overstated. Clicking onto a desktop icon can launch a small standalone app for use in conjunction with other software leviathan. Using tcl/tk apps in such a way needs some sort of persistance to repostion the apps to our preferred locations. Well, here's another bit of code to do such a job.

 #---------------
 # config.tcl
 #---------------
 # Created by William J Giddings
 # 19/Feb/2006
 #---------------
 #
 # Function:
 # Simple load and save package for application config files.
 # 
 # Other links:
 # https://wiki.tcl-lang.org/2438
 #---------------

 # enable/disable demo mode
 set DEMO(config) yes

 #---------------
 # open cfg file
 #---------------
 proc config:open {{fname skt.cfg}} {
  global config

  if {[file exists $fname]} {
    set fp [open $fname r]
  } else {
    return 0
  }
  # read line by line
  # respond appropriate to what is found
  # see https://wiki.tcl-lang.org/2438
  while {![eof $fp]} {
    set data [gets $fp]
    switch [lindex $data 0] {
      \# {
        # these are comments
        puts $data
      }
      #
      # place other switch values and commands here..
      #
      geometry {
        # restore last position on screen
        wm geometry [winfo toplevel .txt1] [lindex $data 1]
      }
      background {
        .txt1 config -bg  [lindex $data 1]
      }
      default {
        # restore some other values that might be useful
        set config([lindex $data 0]) [lindex $data 1]
      }
    }
  }
  close $fp
  return 1
 }

 #---------------
 # save cfg file
 #---------------
 proc config:save {{fname skt.cfg}} {
    global config
    set fp [open $fname w]
    # write specific items of information
    puts $fp "# config demo"
    puts $fp "geometry\t[winfo geometry [winfo toplevel .txt1]]"
    # write contents of config array,
    foreach i [array names config] {
      # somehow a enmpty item exists, can some other tcler tell me why?
      if {$i!=""} { 
        puts $fp "$i\t\{$config($i)\}" 
      }
    }   
    close $fp
 }

 #---------------
 # the ubiquitous demo
 #---------------

 proc config:demo {} {
  catch {console show}
  global config

  # set some defaults in case there's no .cfg file
  set config(ver) 0.1
  set config(app) cfg
  set config(bg) #ffffdd

  # create main window and widgets
  # close button
  button .but1 -text Close -command {config:save ; #exit}
  pack   .but1 -fill x -side top -anchor nw

  text .txt1 -bg $config(bg)
  pack .txt1 -fill both -expand 1

  #load config file
  config:open
 }

 if {$DEMO(config)} {
  config:demo
 }

MHo: Matthias Hoffmann - Tcl-Code-Snippets - Misc - Readprof goes in the same direction... dotfile generator