c - Reading the file with comma delimiter using fgets() and strtok() -
i have text file 3 fields separated comma. example of content of text file: 12345, true programming newbie, bs me load file program, used below code.... problem code works , doesn't (no error message appears program closes , doesn't continue). observed text file blank (nothing written) automatically closes , doesn't continue. highly appreciated. thanks!
int read(){ file *stream = null; int ctr; char linebuffer[45]; char delims[]=", "; char *number[3]; char *token = null; stream = fopen("student.txt", "rt"); if (stream == null) stream = fopen("student.txt", "wt"); else { printf("\nreading student list directory. wait moment please..."); while(!feof(stream)){ ctr=0; fgets(linebuffer, 46, stream); token = strtok(linebuffer, delims); while(token != null){ number[ctr] = linebuffer; token = strtok(null, delims); ctr++; } recordctr++; } recordctr--; } fclose(stream); }
you never copy token
once you've found it. can't copy linebuffer
, data in there overwritten next line loaded.
this line:
number[ctr] = linebuffer;
should reference token
save found token, doesn't. should read like1:
strcpy(number[ctr], token);
but you'd have change declaration make sure there's space:
char number[3][32];
obviously, introduces buffer overrun risk, if there's long token won't fit. how best handle left exercise. :)
1 why temporary vector called "number" when used store 2 numbers , 1 string (the name) beyond me.
Comments
Post a Comment