Hi there, I am fairly new to programming and trying create a program to parse csv data into an array. I have been following an example I found on this site but I am running into a segmentation fault (even if I copy code directly). I am fairly sure the problem lies in the while loop, I just cant see it.
****Sample Csv Data****
1.0235, 2.1112, 1.9972
3.0139, 1.1876, 2.91785
1.9295, 2.1322, 2.4821
I realize its probably overkill for my purpose so if anyone could point me to a simpler solution that would be appreciated too.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXFLDS 200 /* maximum possible number of fields */
#define MAXFLDSIZE 32 /* longest possible field + 1 = 31 byte field */
void parse( char *record, char *delim, char arr[][MAXFLDSIZE],int *fldcnt)
{
char*p=strtok(record,delim);
int fld=0;
while(*p)
{
strcpy(arr[fld],p);
fld++;
p=strtok('\0',delim);
}
*fldcnt=fld;
}
int main(int argc, char *argv[])
{
char tmp[1024]={0x0};
int fldcnt=0;
char arr[MAXFLDS][MAXFLDSIZE]={0x0};
int recordcnt=0;
FILE *in=fopen(argv[1],"r"); /* open file on command line */
if(in==NULL)
{
perror("File open error");
exit(EXIT_FAILURE);
}
while(fgets(tmp,sizeof(tmp),in)!=0) /* read a record */
{
int i=0;
recordcnt++;
printf("Record number: %d\n",recordcnt);
parse(tmp,",",arr,&fldcnt); /* whack record into fields */
for(i=0;i<fldcnt;i++)
{ /* print each field */
printf("\tField number: %3d==%s\n",i,arr[i]);
}
}
fclose(in);
return 0;
}