Reading and Writing .INI Files
The simple INI file has been a popular way for applications to persist application data in a human-editable, flat-file. A example INI file is:
; last modified Thursday, July 23 2009 @ 3:59 PM name = Eric Farrar company = Sybase iAnywhere [Car] make = Honda model = Prelude ; “S” trimline year = 1993
While there is no specific standard on how INI files are organized, typically they contain:
- a single flat-file that is arranged into a set of key/value pairs
- pairs can be grouped under section headings
- comments start at a semi-colon, and run to the end of a line
In most cases, an INI file is implemented as a simple way to persist application data and preferences after shutdown. Of course, if an application already contains an embedded database (such as SQL Anywhere), there should be no need to use an INI file since the database is the natural place to persist information. The only times that it would be useful for SQL Anywhere to interface with an INI file is when that file is maintained by an application outside of your control.
I recently ran into such a case, and I wrote of couple of simple procedures to let SQL Anywhere read and write INI files. The code for the two procedures,
write_ini() can be found here.
read_ini() is used to read the contents of a INI file into a temporary table. It makes heavy use of the
REGXP_SUBSTR() function (including the look-ahead and look-behind functionality) to parse the INI file.
read_ini() returns a result set that has a row for each key/value pair (along with its section and comments). For example, assuming the example INI from above is contained in a file called
DETAILS.INI, the following SQL statement produces this result set:
SELECT * INTO "#ini" FROM read_ini('DETAILS.INI'); SELECT * FROM "#ini";
The contents of the INI file can be modified inside this temporary table. For example, to give my car an upgrade I could issue:
UPDATE "#ini" SET "value" = 'Acura' WHERE "section" = 'Car' and "key" = 'make'; UPDATE "#ini" SET "value" = 'TSX', "comment" = '6-speed manual' WHERE "section" = 'Car' and "key" = 'model'; UPDATE "#ini" SET "value" = '2010' WHERE "section" = 'Car' and "key" = 'year';
write_ini() writes the contents of a temporary table out to an INI file. To write back our updated INI file, use:
CALL write_ini('DETAILS.INI', '#ini');
DETAILS.INI now contains:
; last modified Thursday, July 23 2009 @ 4:02 PM company = Sybase iAnywhere name = Eric Farrar [Car] make = Acura model = TSX ; 6-speed manual year = 2010
Since INI files are not standard, the procedure may have to be tweaked for the specific format of the INI file you intend to read and write.