I am trying to write a general function that will read in parameters from formatted text file. I want it to be flexible enough that the parameter list can vary. What is the best way to accomplish this in C?
I've been struggling with this for a few days. The strings that I'm able to extract from the file are not what I expected. The sample text file I'm using to debug is simple:
Nx : 1600;
Ny : 400;
dx : .524584;
dy : .25;
dt : 1;
My program is below.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char * argv[])
{
if(argc!=2)
{
printf("ERROR: Usage: ./Practice3 <input file>");
}
else
{
FILE * fr = fopen(argv[1], "rt");
if(fr == NULL){printf("file %s not found", argv[1]);}
char * tmpstr1 ;
char * tmpstr2 ;
char * delimPtr;
char * endPtr;
int Nx = 0;
int Ny = 0;
double dx = 0;
double dy = 0;
char tempbuff[100];
while(!feof(fr))
{
if (fgets(tempbuff,100,fr)) {
delimPtr = strstr(tempbuff,":");
endPtr = strstr(delimPtr,";");
strncpy(tmpstr1,tempbuff,delimPtr-tempbuff);
strncpy(tmpstr2,delimPtr+2 ,endPtr-delimPtr-2);
printf("<<%s>>\n", tmpstr1);
printf("<<%s>>\n", tmpstr2);
if (strcmp(tmpstr1,"Nx")==0) {
Nx = atoi(tmpstr2);
}
else if (strcmp(tmpstr1,"Ny")==0) {
Ny = atoi(tmpstr2);
}
else if (strcmp(tmpstr1,"dx")==0) {
dx = atof(tmpstr2);
}
else if (strcmp(tmpstr1,"dy")==0) {
dy = atof(tmpstr2);
}
else{
printf("Unrecongized parameter : \"%s\"\n", tmpstr1);
}
}
}
fclose(fr);
printf("\nNx : %d \nNy : %d \ndx : %f \ndy : %f \n", Nx,Ny,dx,dy);
}//end of code executed when input is correct
}
I am compiling with gcc -std=c99. The tmpstr1 variable prints out with a weird blob character at the end. I can't reliably extract the parameter name the way I have it now. What is a better way?
Also, it seems that tmpstr2 doesn't get overwritten completely from strncpy so the numbers are getting mixed up. It seems like C is not designed to do this kind of sting manipulation easily. But I have to use C for class so I'm stuck. Any ideas?