zach adams
zach adams

Reputation: 29

How to read in variable names and their corresponding values in C

I've been searching all over and cannot figure out how to do this. I am trying to read in a text file with contents like

x 4
y 6
z 9

and set the int values to the corresponding variable name before it; is there anyway to do this or do I have to assign the names in the program after reading in the values.

Upvotes: 1

Views: 212

Answers (2)

the kamilz
the kamilz

Reputation: 1988

I think you are asking for dynamic code generator those I used for different purpose back then (generating long byte arrays with certain values). The generator will generate a .c file with variable names read from another file. This problem is, it's hard to do this for runtime, if you asking for runtime solution, other dudes are already given the answer.

Upvotes: 0

Shadow Radiance
Shadow Radiance

Reputation: 1369

There are a couple of methods you could use to get the data into the program associated with a name, depending on how your program is structured.

If your program doesn't contain variables with those names already, then there's not a way to generate variables from a file. You could create a dictionary mapping the names to the values and use that as your "variable".

I suppose you could also have a dictionary mapping the names to the addresses of existing variables... so that you look up the name and then deref the variable to set if its in the dictionary.

As a really far-out solution... if you can recompile each time there is a new file (ie. the file is really compile-time input, not run-time input) then you might be able to use some kind of preprocessing to #include the (possibly itself preprocessed into c-code) file of data.

Upvotes: 2

Related Questions