I have a struct OPTS
which contains a few char
s 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.
-
1\$\begingroup\$ You may want to take a look to this SO post: stackoverflow.com/a/17174467/1207195 \$\endgroup\$Adriano Repetti– Adriano Repetti2016年11月10日 15:00:24 +00:00Commented Nov 10, 2016 at 15:00
2 Answers 2
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.
This may fit perfectly depending on the purposes, or you could use another approach to be more efficient, clean or consistent.
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.
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
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.