Hello,
I am trying to use a switch statement to read data from a text file. Text File is laid out as follows:
Code:
val1=1
val2=2
...
string1=help
string2=please
My code (as shown below) will not compile because it says that my case expression has to be a constant. I thought I did make it a constant. Any suggestions?
Also, is this the best method to read data from a text file and assign it to a variable within a program?
Thanks!
Code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define IniTestFile "test.ini"
#define TestLogFile "test.log"
static FILE *ini_file;
static FILE *log_file;
int main(void)
{
int total = 0, value1 = 0, value2 = 0;
if ((log_file = fopen(TestLogFile, "a+") ) == NULL)
fprintf (stderr, "\nERROR - Cannot open <%s>\n", TestLogFile);
else{
fprintf(log_file, "\nProgram starting");
}
if ((ini_file = fopen(IniTestFile, "r") ) == NULL)
fprintf (stderr, "\nERROR - Cannot open <%s>\n", IniTestFile);
else{
fprintf(log_file, "\nIni File Open");
}
const char var1[4], val1[4], val2[4];
int var2;
char Variable = fscanf(ini_file, "%[^=] %s", var1, &var2 );
while ( Variable =! EOF ) {
Variable = fscanf( ini_file, "%[^=] %s", var1, &var2 );
switch ( var1 ) {
case "val1":
value1 = var2;
break;
case "val2":
value2 = var2;
break;
}
}
total = value1 + value2;
fprintf(log_file, "\nTotal is: %d", total);
fclose(log_file);
fclose(ini_file);
return 0;
}