I have the following code, which tokenises a file of the form:
Code:
Air density (kg/m3) = 1.225
Mass (kg) = 500
Engine power (HP) = 100
etc.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// FUNCTIONS
int linecount(char filename[40])
{
FILE *countfile;
int ch=0;
int lineno=0;
countfile=fopen(filename,"r");
// Count number of lines and length of file
while ((ch = fgetc(countfile)) != EOF) if (ch == '\n') ++lineno;
fclose(countfile);
return (lineno);
}
// Checks if import file has been opened correctly.
void importnullcheck(char filename[30])
{
FILE *fileopen;
fileopen=fopen(filename,"r");
if (fileopen==NULL) fprintf(stdout,"Could not open %s file to read. Check the filename is correct.\n",filename);
fclose(fileopen);
}
main()
{
char delims[]="=";
char paramfilename[20],line[128];
char *param;
int paramlineno,i;
FILE *parameters;
float m,rho,P;
fprintf(stdout,"\nType in the name and extension of the aircraft data file e.g. param.txt\n");
scanf("%25s",paramfilename);
importnullcheck(paramfilename);
paramlineno=linecount(paramfilename);
// Open parameters file
parameters=fopen(paramfilename,"r");
fseek(parameters, 0, SEEK_SET);
i=0;
while(fgets(line,sizeof line,parameters) !=NULL)
{
param=strtok(line,delims);
if (strcmp("Mass (kg) ",param)==0)
{ param=strtok(NULL,delims);
m=atof(param);}
if (strcmp("Air density (kg/m3) ",param)==0)
{ param=strtok(NULL,delims);
rho=atof(param);}
if (strcmp("Engine power (HP) ",param)==0)
{ param=strtok(NULL,delims);
P=atof(param);}
// etc. -about 30 different parameters.
}
fprintf(stdout,"Air density is %lf kg/m3\n",rho);
fprintf(stdout,"Mass is %lf kg\n",m);
fprintf(stdout,"Power is %lf HP\n",P);
// etc.
fclose(parameters);
return(0);
}
The output when this is run is:
Code:
Type in the name and extension of the aircraft data file e.g. param.txt
param.txt
Air density is 1.225000 kg/m3
Mass is 500.000000 kg
Power is 100.000000 HP
This is correct. What's the reason the above works, but putting it in a function:
Code:
// FUNCTION
float ftokencomp(char string[12],char *comparison)
{
char delims[]="=";
if (strcmp(string,comparison)==0) comparison=strtok(NULL,delims);
return(atof(comparison));
}
Then putting
Code:
m=ftokencomp("Mass (kg) ",param); // in the tokenising 'while' loop
fails? It compiles but the output is now
Code:
Type in the name and extension of the aircraft data file e.g. param.txt
param.txt
Air density is 1.225000 kg/m3
Mass is 0.0000000 kg
Power is 100.000000 HP
Obviously something is wrong with my function, can anyone see the problem?
Thanks in advance.