Skip to content

Instantly share code, notes, and snippets.

@andydude
Last active April 25, 2019 06:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andydude/6c4523bcbf2feb90d5bd7a209dfd3108 to your computer and use it in GitHub Desktop.
Save andydude/6c4523bcbf2feb90d5bd7a209dfd3108 to your computer and use it in GitHub Desktop.
Config Reader
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void
strvec_slurp (char **envstrvec, size_t size, size_t nitems,
const char *filename)
{
FILE *fp = fopen (filename, "r");
int i;
for (i = 0; envstrvec[i] && i < nitems; ++i)
if (!fgets (envstrvec[i], size, fp))
break;
fclose (fp);
}
char *
strvec_get (char **envstrvec, const char *name)
{
int i;
int len;
char *comtq;
char *nameq;
char *value;
for (i = 0; envstrvec[i]; i++)
{
comtq = strchr (envstrvec[i], '#');
if (comtq && comtq == envstrvec[i])
continue;
value = strchr (envstrvec[i], '=');
if (!value)
continue;
nameq = strchr (envstrvec[i], ' ');
if (!nameq || nameq > value)
nameq = envstrvec[i];
else
nameq++;
if (!strncmp (nameq, name, value - nameq))
{
value++;
len = strlen (value);
if (value[len - 1] == '\n')
{
value[len - 1] = '\0';
len--;
}
if (value[len - 1] == '"' && value[0] == '"')
{
value[len - 1] = '\0';
value++;
len -= 2;
}
return value;
}
}
return NULL;
}
int
main (int argc, char *argv[])
{
char envstrbuf[255][255];
char *envstrvec[255];
for (int i = 0; i < 255; ++i)
envstrvec[i] = (char *) &envstrbuf[i];
strvec_slurp (envstrvec, 255, 255, argv[1]);
printf ("MOTD is %s\n", strvec_get (envstrvec, "MOTD"));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment