Lectus: Here is a fully commented source code of an Itcl class to handle config files in your application. It comes with usage example.
# Import the Itcl package for OOP
package require Itcl
namespace import itcl::*
# Define the ConfigFile class which will handle config file operations
class ConfigFile {
# Internal array to store the data in memory
private array set Data {}
# Internal variable to store the file name in memory
private variable fname ""
# Internal variable to hold the field list
private variable fieldlist ""
# Helper function to wrap the funcionality of reading a full text file
private method read-file {f} {set fd [open $f r]; read $fd}
# Helper function to wrap the funcionality of writing a full text file
private method write-file {f txt} {set fd [open $f w]; puts $fd $txt; close $fd;}
# Constructor that gets called when we create a new ConfigFile object
# Requires the file name and fields to be passed as args
constructor {filename args} {
set fname $filename
set fieldlist $args
}
# Function to write the data to the array and to file
public method setData {args} {
set temp [list]
# Here we need to accumulate in the temp variable in this way:
# "field1 value1 field2 value2"
foreach arg $args field $fieldlist {
lappend temp $field $arg
}
array set Data $temp
write-file $fname [array get Data]
}
# Function to get the data from the file
public method getData {} {
array set Data [read-file $fname]
return [array get Data]
}
# Function to clean the array and delete the file from disk
public method cleanData {} {
array set Data {}
file delete $fname
}
}
#Usage
# Creating a new ConfigFile object
# We pass the object name, the file name and a variable number of fields
ConfigFile conf conf.txt name age phone
# Storing Data
conf setData John 30 328933424
# At this point you could close the application and read it later. It's stored in a file.
# Reading the data from the file
array set Person [conf getData]
# Displaying the data that was read.
parray Person
# Deleting config file
conf cleanDataOf course this is just a simple code. I wanted to write it to help people out there with Itcl, arrays and file handling.
Googie - Just optimized it a little. This is a good example of cool foreach construction in "setData" method. Actually I switched "temp" variable to be a list. This doesn't make whitespace to appear at the begining and also it's safe for any field name and any value (with spaces, special chars, etc).
Lectus: Thanks. Looks better now. Yeah, foreach is really powerful. Tcl handles serialization of lists very easily, that makes it possible to write lists directly to files or sockets. This code in another language would probably be a lot bigger with lots of complex conversions between types.