1

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.

13
  • 1
    What is the question? How to read a file? How to assign a variable? Commented Jan 23, 2018 at 22:28
  • 6
    you have to do it the hard way, c does not have any reflection capabilities Commented Jan 23, 2018 at 22:28
  • 2
    I think you're looking for a dictionary - stackoverflow.com/questions/4384359/…, does that look right? Commented Jan 23, 2018 at 22:29
  • 2
    no "easy" way to do this. If you know the variable names ahead of time simply declare int x, y, z; in your code and assign the appropriate one when you parse the file. A linked list with struct node{ char* varName; int varValue; }; is also an option, but that is overkill. Commented Jan 23, 2018 at 22:38
  • 1
    Sounds like an XY Problem. What problem are you actually trying to resolve? Commented Jan 23, 2018 at 23:02

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.