Config file to struct in C 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-&gt;opt1 = topper(work[6]);
   }
   if (!strncmp (work, "OPTS2=", 6) ) {
      sprintf(optptr-&gt;opt2, "%-4.4s", &amp;work[6]);
   }
   if (!strncmp (work, "OPTS3=", 6) ) {
      optptr-&gt;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.
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.