I figured it out yay!
For completeness and to help anyone with the same problem in future my code is:
Code:
/* Prints all components of a colon delimited file, first into lines then into structures for the words on each line */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
main ()
{
FILE *fs;
char filename,*data;
long fsize; /* size of file */
char* sptr;
int i,j;
int ch=0;
int lineno=0;
char line[128]={'\0'};
char arra[128][128]={{'\0'}};
/* Get file */
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");
if (fs == NULL)
{ printf("Could not open file.\n");
}
else
{
/* Count number of lines and length of file */
while ((ch = fgetc(fs)) != EOF)
{
if (ch == '\n')
++lineno;
}
printf("Number of lines is %d\n", lineno+1);
fseek(fs, 0, SEEK_END);
fsize = ftell(fs);
fseek(fs, 0, SEEK_SET);
printf("File size is %ld characters including end of line characters\n",fsize);
/**********************************************************
Allocate memory for file - probably not needed!
char *data =(char *)calloc(fsize,sizeof(char));
fread(data,fsize,sizeof(char),fs);
if (data==NULL)
{printf("Could not copy into memory");}
else
{
printf("Memory was allocated and file was copied into memory.\n\n");
printf("File is:\n%s\n",data);
***********************************************************/
/* Split into separate lines */
i=0;
while(fgets(line,sizeof line,fs) !=NULL)
{
strcpy (arra[i],line);
/*********************************************************
Code for checking: prints out lines
printf("Line number %d: %s\n",i+1,arra[i]);
**********************************************************/
i++;
}
/* Tokenise by colon delimiter and put into structure */
struct part
{
char name[51];
char value[5];
char unit[5];
} partlist[3000]; /* array of structures to store all line's worth of parts: */
char delims[] = ":"; /* delimiter within line */
i=0;
while (i<=lineno)
{
strcpy(partlist[i+1].name, strtok(arra[i],delims));
strcpy(partlist[i+1].value, strtok(NULL,delims));
strcpy(partlist[i+1].unit, strtok(NULL,delims));
i++;
}
for (i=1; i<=(lineno+1);)
{
printf("Struct %d Name: %s\n", i, partlist[i].name);
printf("Struct %d Value: %s\n", i, partlist[i].value);
printf("Struct %d Unit: %s\n", i, partlist[i].unit);
i++;
}
fclose(fs);
/* keep if calloc is kept */
/* free(data); */
}
return(0);
}
Which can be tested with an example data file of:
Code:
sparlength:4:m
sparxsection:0.2:m2
panellength:2:m
panelxsection:0.03:m2
windowlength:0.5:m
windowxsection:0.05:m2
enginemass:65:kg
Thanks everyone for your help, I'm glad my first week of C ended so well.