Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdlib.h>
- #include <stdio.h>
- #include <string.h>
- #define MAX_LINE_LENGTH 255
- typedef struct
- {
- int exposureTime;
- int flashPin;
- int triggerPin;
- int lightPin;
- double disDropLight;
- double disLightCam;
- } Config;
- typedef struct
- {
- char key[255];
- char value[255];
- } KeyValuePair;
- // declarations
- void addToConfig(Config *config, KeyValuePair pair);
- KeyValuePair getKeyValuePair(char line[MAX_LINE_LENGTH]);
- Config readConfigFromFile();
- int main()
- {
- Config config = readConfigFromFile();
- printf("%s: %d\n", "exposureTime", config.exposureTime);
- printf("%s: %d\n", "flashPin", config.flashPin);
- printf("%s: %d\n", "triggerPin", config.triggerPin);
- printf("%s: %d\n", "lightPin", config.lightPin);
- printf("%s: %f\n", "disDropLight", config.disDropLight);
- printf("%s: %f\n", "disLightCam", config.disLightCam);
- return 0;
- }
- Config readConfigFromFile()
- {
- FILE *file;
- Config config;
- file = fopen("init", "r");
- if (file == NULL)
- {
- perror("fopen()");
- return config;
- }
- // read config file line by line
- char line[MAX_LINE_LENGTH];
- while (fgets(line, MAX_LINE_LENGTH, file))
- {
- // remove trailing newline
- line[strcspn(line, "\n")] = 0;
- // extract key value pair
- KeyValuePair pair = getKeyValuePair(line);
- // fill config struct
- addToConfig(&config, pair);
- }
- fclose(file);
- return config;
- }
- KeyValuePair getKeyValuePair(char line[MAX_LINE_LENGTH])
- {
- char *delimiter = " ";
- KeyValuePair pair;
- int currentToken = 0; // ugh, i hate that - but I need to know which token I'm at and couldn't find a nicer way
- for (char *token = strtok(line, delimiter); token != NULL; token = strtok(NULL, delimiter))
- {
- // take the first token as key ...
- if (currentToken == 0)
- {
- strcpy(pair.key, token);
- }
- // ... and the second as value ...
- else if (currentToken == 1)
- {
- strcpy(pair.value, token);
- }
- // ... and ignore all other tokens.
- else
- {
- break;
- }
- currentToken++;
- }
- return pair;
- }
- void addToConfig(Config *config, KeyValuePair pair)
- {
- if (strcmp(pair.key, "exposureTime") == 0)
- {
- config->exposureTime = atof(pair.value);
- }
- else if (strcmp(pair.key, "flashPin") == 0)
- {
- config->lightPin = atof(pair.value);
- }
- else if (strcmp(pair.key, "triggerPin") == 0)
- {
- config->triggerPin = atof(pair.value);
- }
- else if (strcmp(pair.key, "lightPin") == 0)
- {
- config->lightPin = atof(pair.value);
- }
- else if (strcmp(pair.key, "disDropLight") == 0)
- {
- config->disDropLight = atof(pair.value);
- }
- else if (strcmp(pair.key, "disLightCam") == 0)
- {
- config->disLightCam = atof(pair.value);
- }
- else
- {
- printf("unknown config key: %s\n", pair.key);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment