2
\$\begingroup\$

I have a struct OPTS which contains a few chars and char[]s. I also have a file opts.cnf which can be edited in a text editor like vim. I want to read the opts.cnf and assign the values from that file to my struct.

opts.h

typedef struct OPTS {
  char opt1;
  char opt2[6];
  char opt3;
}

opts.cnf

OPT1=Y
OPT2=1234
OPT3=D

opts.c

while (fgets (work, sizeof (work), file) ) {
   if (!strncmp (work, "OPTS1=", 6) ) {
      optptr->opt1 = topper(work[6]);
   }
   if (!strncmp (work, "OPTS2=", 6) ) {
      sprintf(optptr->opt2, "%-4.4s", &work[6]);
   }
   if (!strncmp (work, "OPTS3=", 6) ) {
      optptr->opt3 = topper(work[6]);
   }
}

Is there a more efficient way to go about this? I need to be able to edit opts.cnf inside of a text editor but different formats are welcome if they make it more efficient.

\$\endgroup\$
2
\$\begingroup\$

Superficially you're existing approach will work for the short number of items you are reading. However it looks somewhat brittle. What happens if the file is edited so that instead of:

OPT1=Y

The user puts:

OPT1= Y

Suddenly you're setting opt1 to ' ' instead of 'Y'.

There's obvious duplication in your code, which will expand if you start reading more items / add more flexible parsing and error checking into the read. I would tend to write a function for splitting the input into two parts, the option name and the option value. I'd then write a function for parsing each type of option value (string, number, character). This would allow error checking to be done once, rather than for each specific value read. Whether or not this is needed depends on how much you trust your users to edit the file correctly.

\$\endgroup\$
2
\$\begingroup\$

This may fit perfectly depending on the purposes, or you could use another approach to be more efficient, clean or consistent.

  1. If you just need to set a few variables of a project, and you don't mind running opts.c every time you change opts.cnf

    Well, your existing solution fits perfectly.

  2. If you are using ops.cnf to set some variables or constants at compilation time.

    In this case, you may have to use #include and #define

  3. If you are planning to use configuration file(s) for different sort of things in your project.

    In this case I would recommend libconfig. Maybe LUA or even Javascript.

Depending on your needs.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.