Hi,
Im doing a project where I make a CSV reader in plain old C. Ive got some great code snippets through helpful users on the internet, but after experimenting I have found I have been unable to join the snippets into a working program.
Basic code structure
This is my code that stores my CSV file contents and stores them in the memory:Code:#include <stdio.h> int main(int argc, char ** argv){ int c; FILE * fp; if(argc < 2){ printf("Usage:\n\t%s filename\n",argv[0]); return -1; } if((fp = fopen(argv[1],"rb")) == NULL){ printf("can't open %s\n",argv[1]); return -2; } while((c = fgetc(fp)) != EOF){ /* TO DO- Put your code to parse the csv here char by char */ printf("%c",c); } fclose(fp); return 0; }
This is my code that is designed to read the CSV data:Code:#define MAX_LINE_LEN 1024*512 /* 1/2 mega byte, should be more than sufficient */ ..... char line[MAX_LINE_LEN]; int len=0; int cnt_of_fields=0; char *p; while( (c=GET_A_CHAR_FROM_FILE(fp))!=EOF){ switch(c) { case '"': case '\'': /* parse a quoted string, ignore it for now */ break; case ',': ++cnt_of_fields; /* a comma signal end of previous field and begining of next fields */ line[len++]='\0'; if(len==MAX_LINE_LEN){ fprintf(stderr, "Line too long\n"); exit(-1); } break; case '\n': ++cnt_of_fields; /* a EOL is end of record, and at the same time end of field */ line[len++]='\0'; /* make a copy of the line in the heap, note strdup or strcpy won't work in our case */ p = (char *)malloc(len); memcpy(p, line, len); /* now all the fields in the record are stored in p[ ] */ add_a_record( p ); break; default: line[len++] = c; if(len==MAX_LINE_LEN){ fprintf(stderr, "Line too long\n"); exit(-1); } } }
Code:printf( "%s", line );



LinkBack URL
About LinkBacks


