Version 0 of Itcl class to store data in files using arrays

Updated 2011-11-25 14:27:41 by Lectus

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 ""
                set count 0
                # Here we need to accumulate in the temp variable in this way:
                # "field1 value1 field2 value2"
                foreach arg $args {
                        set temp "$temp [lindex $fieldlist $count] $arg"
                        incr count
                }
                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 cleanData

Of course this is just a simple code. I wanted to write it to help people out there with Itcl, arrays and file handling.