Hello,
When I tried to run my code I keep getting a "Segmentation fault". I don't know what I am doing wrong. Can someone help me?
I am trying to write a code that read from a file and put the data into a structure.
The file look like the following:
2001,ABBIGAEL,5
1994,ABBIGAIL,5
1996,ABBIGAIL,8
1997,ABBIGAIL,13
The file have 31 lines.
Here is my code:
Code:
#include <stdio.h>
#include <string.h>
int main() {
/* Define a daydata structure */
typedef struct {
int year; int freq;
char name[31];
} daydata ;
daydata record[40];
FILE * filehandle;
char lyne[121];
char *item;
int reccount = 0;
int k;
/* Here comes the actions! */
/* open file */
filehandle = fopen("female.csv","r");
/* Read file line by line */
while (fgets(lyne,120,filehandle)) {
printf("%s",lyne);
item = strtok(lyne,",");
record[reccount].year= atoi(item);
item = strtok(NULL,",");
strcpy(record[reccount].name,item);
item = strtok(NULL,"\n");
record[reccount].freq= atoi(item);
printf("%d\n",record[reccount].year);
reccount++;
}
/* Close file */
fclose(filehandle);
/* Loop through and report on data */
printf("Name Record\n");
for (k=0; k<reccount; k++) {
printf("It is %s\n",record[k].name);
}
}
OUTOUT:
2001,ABBIGAEL,5
2001
1994,ABBIGAIL,5
1994
1996,ABBIGAIL,8
1996
1997,ABBIGAIL,13
1997
1998,ABBIGAIL,18
1998
1999,ABBIGAIL,15
1999
2000,ABBIGAIL,13
2000
2001,ABBIGAIL,17
2001
2002,ABBIGAIL,23
2002
2003,ABBIGAIL,20
2003
2004,ABBIGAIL,17
2004
2005,ABBIGAIL,36
2005
2006,ABBIGAIL,26
2006
2007,ABBIGAIL,23
2007
2008,ABBIGAIL,34
2008
Segmentation fault
Thank you.