How to separate and store elements from a string in c? -
i have open .txt file. suppose content of file is:
08123, (12/10/2010,m), (01/09/1990,d)
i want store in different parameters of string 08123
, "12/10/2010"
, 'm'
, example:
int code = 08123; char date[10] = '12/10/2010'; char day = 'm';
also, last argument finishes )
. how can iterate until line ends?
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct date { char date[11];//+1 '\0'. char day; } date; typedef struct rec { int code; int dc;//number of date date *dates; } record; record *parse_rec(char *line){ static const char *sep = ", "; static const int seplen = 2;//strlen(sep); record *rec = malloc(sizeof(*rec)); if(rec){ int i, count = 0; char *p; for(p=strstr(line, sep);p;p = strstr(p+seplen, sep)){ ++count; } rec->dc = count; rec->dates = malloc(count*sizeof(date)); rec->code = atoi(line); line = strstr(line, sep) + seplen; for(i=0;i<count;++i){ sscanf(line, "(%[^,],%c", rec->dates[i].date, &rec->dates[i].day); line = strstr(line, sep) + seplen; } } return rec; } int main(void){ char line[1024]; file *fp = fopen("data.txt", "r"); fgets(line, sizeof(line), fp); fclose(fp); record *rec = parse_rec(line); printf("code: %05d\n", rec->code); for(int i=0;i < rec->dc; ++i){ printf("date : %s\n", rec->dates[i].date); printf(" day : %c\n", rec->dates[i].day); } free(rec->dates); free(rec); return 0; }
Comments
Post a Comment