Re: Variable-sized lines of text in linked list




Scottman <FonzoCool@xxxxxxxxx> wrote in message
news:1fe49f6a-2abf-419d-9008-99ee0fc6cee7@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

I am trying to read a text file into memory without any knowledge of
how long each line will be. I am looking to store each line in a
linked list structure, however, I am unsure of how to dynamically
allocate space for each line.

Maybe you don't have to malloc each line, but rather just the entire
file, with pointers to the start of each line, and replace each newline
with a terminating null (this decision will impact how easily you can
process the lines after you've stored them this way, but just throwing
out an idea that doesn't seem to be getting much play here).

This is how I set up the linked list...

typedef struct node {
char *line;

OK, but this can just be a pointer to the first character of each line
in what is essentially the entire file...right?

struct node *next;
} linkedlist;

OK, then in psuedo-code and hand-waving...

linkedlist* createlinkedlist(void) {
unsigned num_nodes=0;
size_t num_chars=0;
int current_char;

open_file_for_reading

num_chars=count_each_character_in_file(file_pointer)

rewind_file_pointer

file_memory=malloc_file_memory(num_chars)

malloc_list_head

list_head->line=file_memory

num_chars=0

read_each_character_in_file_to_memory_until_end_of_file {

if(current_char=='\n') {

current_char='\0'
malloc_next_node
next_node->line=file_memory+num_chars+1
}

num_chars++
}
}

....or something like that...

---
William Ernest Reid



.