> head is the pointer to the first node and tail to the last. Why is it poor?
> buffer->head=fgets(line,MAXLINE,fp);
See the answer yet?
Try this
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct node {
char *line;
struct node *prev;
struct node *next;
};
struct list {
struct node *head;
struct node *tail;
int size;
int currentpos;
char *current;
};
struct node *makeNode ( char *line ) {
struct node *new = malloc ( sizeof *new );
if ( new ) {
/* initialise a node */
new->prev = NULL;
new->next = NULL;
new->line = malloc ( strlen(line) + 1 ); /* should check NULL */
strcpy ( new->line, line );
}
return new;
}
void appendlist ( struct list *list, char *line ) {
struct node *new = makeNode ( line );
/* now add it to the list */
if ( list->head == NULL ) {
/* easy, list is empty */
list->head = new;
list->tail = new;
list->size = 1;
} else {
/* fix the tail node of the list */
list->tail->next = new;
/* fix the previous of the new node */
new->prev = list->tail;
/* move the tail forward */
list->tail = new;
list->size++;
}
}
void ReadFile ( struct list *list, char *filename ) {
char buff[BUFSIZ];
FILE *fp = fopen( filename, "r" );
while ( fgets ( buff, BUFSIZ, fp ) != NULL ) {
appendlist ( list, buff );
}
fclose ( fp );
}
void WriteFile ( struct list *list, char *filename ) {
FILE *fp = fopen( filename, "w" );
struct node *p = list->head;
printf( "List as %d nodes\n", list->size );
while ( p != NULL ) {
fputs ( p->line, fp );
p = p->next;
}
fclose ( fp );
}
int main ( ) {
struct list mylist = { 0, 0, 0, 0, 0 }; /* empty list */
ReadFile ( &mylist, "foo.c" );
WriteFile ( &mylist, "bar.c" );
return 0;
}