Henk wrote On 09/29/05 11:02,:
Hi,
I am new to the c-programming language and at the moment I am
struggling with the following:
I want to read a file using fread() and then put it in to memory. I
want to use a (singel) linked list to continousely (dynamically) free
up more memory when needed and put the buffers with the data of the
file on a sort of stack.
The problem is that i have no idea how to do this.
My question is: Does anyone of you have an example of how to read in an
file and put it into memory using a singel linked list or maybe know a
site where I can find an example?
One way is to use a struct object to hold each
chunk of data, plus a pointer to the struct that
holds the next chunk:
struct chunk {
struct chunk_s *next;
Whatever data;
};
You'll also need a pointer to the first chunk
so you can find the start of the list after you're
done reading, and a pointer to the last chunk read
so far so you know where to add the next one, and
a pointer to the chunk you're currently reading:
struct chunk *head = NULL;
struct chunk *tail;
struct chunk *this;
To read the data, you'll allocate memory for a
chunk and read into its `data' portion. If there's
nothing left to read, discard the unused chunk and
return `head' as a pointer to the start of the list.
Otherwise, append the newly-read chunk to the list
and repeat:
for (;;) {
this = malloc(sizeof *this);
if (this == NULL)
... die ...
... read into `this->data' ...
if (... end of file ...) {
free (this);
return head;
}
if (... I/O error ...)
... die ...
if (head == NULL) /* the first chunk */
head = this;
else /* subsequent chunks */
tail->next = this;
tail = this;
this->next = NULL;
}
There are lots of variations on this approach.
For example, you can do get rid of the `tail' pointer
and the `if (head == NULL)' stuff by building the list
backwards and then reversing it before returning. Or
there might be a `size' field in the `struct chunk' to
state how much of the `data' is actually used. Or ...
--
Er*********@sun.com