1. Computing & Technology

Discuss in my forum

C Programming Tutorial - Text File Handling

By , About.com Guide

8 of 10

An example of reading a Config File
Example 9 is a library plus test program that reads a config file, constructs a data structure in memory and lets you access elements from the file. It's organized as a number of sections, with each section having 0 or more Name=Value pairs. Value is just a text string and there is no associated type. It's up to your application to make sense of it. Everything after the = to the end of the line is taken as the value. Here is a typical config file:
 ; blank lines are skipped, as is any line starting with a ; is a comment
 
 [Section 1]
 alpha=1
 beta=two
 gamma=34.5
 
 [Section 2]
 delta=300
 assign_printer=Y
 logic=True
 
The same name can be used in different sections.

The library consists of a number of functions to open the library and build a structure in memory. The initlib function is passed the name of the file and reads it line by line. The data structure is a linked list of named sections. In the config file these have names like [Section 1] etc and in that case Section 1 is stored out as the name of the section.

After the library has opened successfully, head will have a non zero value, pointing to the first section in memory. I've kept error checking to a bare minimum so if it can't open the file etc, it will just fail with an error.

There are several functions provided to access the config file.

  • isname(section,name) returns true (a non zero int) is the specified name value exists in the specified section.
  • findsection(sectionname) returns NULL or a pointer to the section if the named section exists. Also sets current.
  • getvalue(name) - this needs current to be pointing to a section. It returns the value cfor the specified name.

On the next page: How It Works

©2012 About.com. All rights reserved.

A part of The New York Times Company.