Dynamic access to struct field names

A

Andrew Fabbro

I think FAQ 2.15 ("How can I access structure fields by name at run
time?") answers my question, but I don't like the answer ;)

I have a struct like this:

struct config_struct {
char file_dir[MAXPATHLEN];
char debug_dir[MAXPATHLEN];
/* and many more */
} config;

I have a text file like this:

file_dir /usr/local/blah/file/
debug_dir /usr/local/blah/debug

Parsing this is easy, but populating the config struct is not. Well,
it's easy but not fun. What I want is something like (pseudocode):

read in option_name, option_value
config.(option_name) = option_value (be it by strcpy or whatever)

It appears there's no way to do this in C. I've looked at some code
written by far wiser minds than I, and they do a lot of

if ( strcmp(option_name, "file_dir") == 0 )
strcpy(config.file_dir, option_value);

and such. I suppose I could keep an array of field names and their
sizeofs and then jump around with a pointer...is that really the best
way?

-Drew
 
J

Jack Klein

I think FAQ 2.15 ("How can I access structure fields by name at run
time?") answers my question, but I don't like the answer ;)

I have a struct like this:

struct config_struct {
char file_dir[MAXPATHLEN];
char debug_dir[MAXPATHLEN];
/* and many more */
} config;

I have a text file like this:

file_dir /usr/local/blah/file/
debug_dir /usr/local/blah/debug

Parsing this is easy, but populating the config struct is not. Well,
it's easy but not fun. What I want is something like (pseudocode):

read in option_name, option_value
config.(option_name) = option_value (be it by strcpy or whatever)

It appears there's no way to do this in C. I've looked at some code
written by far wiser minds than I, and they do a lot of

if ( strcmp(option_name, "file_dir") == 0 )
strcpy(config.file_dir, option_value);

and such. I suppose I could keep an array of field names and their
sizeofs and then jump around with a pointer...is that really the best
way?

-Drew

If the number of possible names are small, that is probably the best
way.

If the number of possible names are large and efficiency is a concern,
make an array of structures consisting of a pointer to string, an enum
for different data types, and a ptrdiff_t for the member's offset in
the structure generated by the standard offsetof macro. Sort the
array before placing in the source, and bsearch() it to match the
string.

It's icky, but perfectly standard and legal C.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top