In <200908210055.17041.drankinatty@suddenlinkmail.com>, David C. Rankin wrote:
On Friday 21 August 2009 12:07:49 am Boyd Stephen Smith Jr. wrote:
You might want to build your "array, list, whatever" while you are counting the lines though.
I thought about that, but I was going to dynamically allocate the pointer array so I thought I would need to scan the buffer first to know how many pointers to allocate? (I haven't got there yet, so maybe that is the whacky part of my thinking ;-)
realloc() is your friend if you need to grow an array. Example code: int find_lines_array( /* IN */ char *wholeFile, /* IN */ size_t fileSize, /* OUT */ char *(*lines[]), /* OUT */ size_t *lineCount ) { size_t l_count = 0; char *(*l_lines[]) = NULL; int begOfLine = 1 for (size_t offset = 0; offset < fileSize; ++offset) { if (begOfLine) { if (l_count == SIZE_MAX) { free(l_lines); return EOVERFLOW; } ++l_count; if (SIZE_MAX / l_count < sizeof((*l_lines)[0])) { free(l_lines); return EOVERFLOW; } l_lines = realloc(l_lines, l_count * sizeof((*l_lines)[0]); if (!l_lines) { /* XXX: Memory Leak */ return ENOMEM; } l_lines[l_count - 1] = wholeFile + offset; begOfLine = 0; } if (wholeFile[offset] = '\n') { begOfLine = 1; } } *lineCount = l_count; *lines = *l_lines; /* FIXME: May not work */ return 0; } Using a linked-list (singly- or doubly-linked) won't even need a realloc. Example code: typedef struct node_t { struct node_t *next; char *line; } node; int find_lines_list( /* IN */ char *wholeFile, /* IN */ size_t fileSize, /* OUT */ node *linesHead, /* OUT */ size_t *linesCount ) { size_t l_count; node *l_head = NULL; node *tail = NULL; int begOfLine = 1; for (size_t offset = 0; offset < fileSize; ++offset) { if (begOfLine) { if (l_count == SIZE_MAX) { /* FIXME: Cleanup; leaks memory ATM. */ return EOVERFLOW; } ++l_count; if (tail) { tail->next = malloc(sizeof(*tail->next)); tail = tail->next; } else { head = tail = malloc(sizeof(*tail)); } if (!tail) { /* FIXME: Cleanup; leaks memory ATM. */ return ENOMEM; } tail->next = NULL; tail->line = wholeFile + offset; } if (wholeFile[offset] = '\n') { begOfLine = 1; } } *linesCount = l_count; *linesHead = *l_head; return 0; } These are just examples, you'll need to add the appropriate headers, and there are clearly some comments that demand more code, but either should get you started. Both have O(fileSize) runtime, which is the best I can imagine for arbitrary files. -- Boyd Stephen Smith Jr. ,= ,-_-. =. bss@iguanasuicide.net ((_/)o o(\_)) ICQ: 514984 YM/AIM: DaTwinkDaddy `-'(. .)`-' http://iguanasuicide.net/ \_/