Re: Variable-sized lines of text in linked list
- From: "cr88192" <cr88192@xxxxxxxxxxx>
- Date: Fri, 29 Feb 2008 07:49:52 +1000
"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.
This is how I set up the linked list...
typedef struct node {
char *line;
struct node *next;
} linkedlist;
linkedlist* createlinkedlist(void) {
linkedlist* head;
head = (linkedlist *)malloc(sizeof(linkedlist));
head->line = NULL;
head->next = NULL;
return head;
}
void addnode(linkedlist* list, char *line) {
linkedlist* freespot;
linkedlist* newnode;
freespot = list;
while (freespot->next != NULL)
freespot = freespot->next;
newnode = (linkedlist *)malloc(sizeof(linkedlist));
newnode->line = line;
newnode->next = NULL;
freespot->next = newnode;
}
So with this in place, how can I read in variable length lines,
malloc() the proper storage for each and pass the pointer to
addnode()?
usual, simplistic approach:
use a largish buffer to read input lines (somewhat longer than the longest "sane" line), alternatively, it can be resized as needed as well;
usually, this can be read with either fgets, or a loop using fgetc (better for the resize approach).
after this, we can use strdup or similar to allocate the exact string (the main buffer is reused for reading each line, thus tending to be either the initial size of the size of the longest line).
most of the time though, I make simplifying assumptions, such as assuming 256 chars is a sane maximum line length (if longer, the line is naturally and arbitrarily broken at this limit by the use of fgets or similar).
another common approach in my case is to allocate a buffer big enough for the whole file, which is read in and processed as such (decomposed into lines or tokens or whatever...).
Thanks!
Cheers,
Scott Nelson
.
- References:
- Variable-sized lines of text in linked list
- From: Scottman
- Variable-sized lines of text in linked list
- Prev by Date: Re: Variable-sized lines of text in linked list
- Next by Date: Re: Legal C or bug in gcc
- Previous by thread: Re: Variable-sized lines of text in linked list (long)
- Next by thread: Re: Variable-sized lines of text in linked list
- Index(es):
Relevant Pages
|