I'm a beginner at C programming but have been tasked with the following:
I have a text file with data in it in the form
variablename:float:units
i.e. colon delimited values.
I need to take the variablename and have it equate to the float number in the middle column. My code at the moment will display the lines of the text file and attempts to deposit characters up to the colon character into a text file 'deposit.c' but I'm not sure how to extract the variable name and the float number and equate them.
My code so far is:
Code:
/* Prints all lines of a file data.txt out with line number */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
main ()
{
FILE *fs,*ft;
int i,j;
char arra[128][128];
char line[128]; /* max. line size */
char filename;
char return_val;
char ch;
printf("Type in the name and extension of the model file e.g. data.txt\n");
scanf("%s",&filename);
printf("Filename is %s\n",&filename);
fs=fopen(&filename,"r"); /* Opens file for reading text */
ft=fopen("deposit.c","w");
for (i=0; i<128; i++)
for (j=0; j<128; j++)
arra[i][j]= '\0';
for (i=0; i<128; i++)
line[i] = '\0';
if (fs !=NULL) /* ! = 'not' */
{
i=0;
while (fgets (line,sizeof line,fs) !=NULL) /* read a line */
{
strcpy(arra[i], line); /* Puts line into into same number array */
printf("Line Number %d: %s", i+1,&arra[i]);
i++;
}
/* Put extra formatting in here */
/* Need to create variable from first column and have it defining the number in the second column */
while(1)
{
ch = fgetc(fs);
if (ch == ':')
break;
else
fputc (ch, ft); /* puts letters up to colon into file ft */
}
fclose(fs);
fclose(ft);
}
else
{ printf("Could not open file\n");
}
return 0;
}
I realise this code is probably not the most efficient way of displaying the lines but that is an intermediate step and the lines will not need to be displayed in the final code.
My data.txt file is
Code:
Aldensity:2700:kg/m3
spar:4:0
rib:8:0
Obviously I could do it manually but the actual file I'll be using is up to 3000 lines.. and my project supervisor wants a program to do it!
Thank you very much for any help.