Sunday 15 April 2012

fscanf in C with a text file with no spaces -



fscanf in C with a text file with no spaces -

i have text file names looks follows:

"mary","patricia","linda","barbara","elizabeth","jennifer","maria","susan","margaret",

i have used next code effort set names array:

char * names[9]; int = 0; file * fp = fopen("names.txt", "r"); (i=0; < 9; i++) { fscanf(fp, "\"%s\",", names[i]); }

the programme comes segmentation fault when seek run it. have debugged carefully, , notice fault comes when seek , read in sec name.

does know why code isn't working, , why segmentation fault happening?

you have undefined behavior in code, because don't allocate memory pointers write in fscanf call.

you have array of 9 uninitialized pointers, , part of local variable have indeterminate value, i.e. point seemingly random locations. writing random locations in memory (which happen when phone call fscanf) bad things.

the simplest way solve problem utilize array of arrays, e.g.

char names[9][20];

this gives array of 9 arrays, each sub-array beingness 20 characters (which allows have names 19 characters long).

to not write out of bounds, should modify phone call don't read many characters:

fscanf(fp, "\"%19s\",", names[i]);

there problem utilize of fscanf function, , format read string, "%s", reads until finds whitespace in input (or until limit reached, if field width provided).

in short: can't utilize fscanf read input.

instead suggest read whole line memory @ once, using fgets, , split string on comma using e.g. strtok.

one way of handling arbitrarily long lines input file (pseudoish-code):

#define size 256 size_t current_size = size; char *buffer = malloc(current_size); buffer[0] = '\0'; // terminator @ first character, makes string empty (;;) { // read temporary buffer char temp[size]; fgets(temp, sizeof(temp), file_pointer); // append actual buffer strcat(buffer, temp); // if lastly character newline (which `fgets` append // if reaches end of line) whole line have // been read , done if (last_character_is_newline(buffer)) break; // still more info read line // allocate larger buffer current_size += size; buffer = realloc(buffer, current_size); // continues loop seek , read next part of line } // after loop pointer `buffer` points memory containing whole line

[note: above code snippet doesn't contain error handling.]

c fscanf

No comments:

Post a Comment