fopen - Read file and save each line to variable in C -
i'm using fgetc , fopen read file in c. i'd first line in variable , second line in separate variable so:
f = fopen("textfile", "r"); if (!f) { printf("error"); } else { loop until end of newline , save entire line variable 1st line ==> line1 2nd line ==> line2 } so if textfile has:
hello world goodbye world line1 = "hello world" line2 = "goodbye world"
i'm thinking of looping until \n how should store characters? think simple question , maybe i'm missing something?
you want to:
i. use fgets() entire line, then
ii. store lines array of array of char.
char buf[0x1000]; size_t alloc_size = 4; size_t n = 0; char **lines = malloc(sizeof(*lines) * alloc_size); // todo: check null while (fgets(buf, sizeof(buf), f) != null) { if (++n > alloc_size) { alloc_size *= 2; char **tmp = realloc(lines, sizeof(*lines) * alloc_size); if (tmp != null) { lines = tmp; } else { free(lines); break; // error } lines[n - 1] = strdup(buf); } }
Comments
Post a Comment