cs240/labs/lab12/file.c
2018-10-15 17:20:57 -04:00

70 lines
1.5 KiB
C

#include "file.h"
/* how we print your linked list to test if it is correct or not*/
void print(){
node *ptr = head;
while(ptr != NULL){
printf("%d->",ptr->data);
ptr = ptr->next;
}
printf("\n");
}
/* function to add a node to the list for you use in fwrite*/
void append(node * n){
n->next = head->next;
head->next = n;
}
/*function to get the last node for you to allow you to save it a file*/
node * getLast(){
if(!head->next){
return NULL;
}
node * ptr = head->next->next;
node * tmp = head->next;
node * prev = head;
while(ptr != NULL){
prev = tmp;
tmp = ptr;
ptr = ptr->next;
}
prev->next = NULL;
return tmp;
}
/* read a node from file until you reach an EOF. Each node you read please save to the linked list with append()*/
void read_node(char * filename){
FILE* in = fopen(filename, "rb");
node* item = (node *) malloc(sizeof(node));
int bytesRead = fread(item, sizeof(node), 1, in);
while (bytesRead > 0) {
append(item);
item = (node *) malloc(sizeof(node));
bytesRead = fread(item, sizeof(node), 1, in);
}
fclose(in);
}
/* USING get last keep writing to file until getLast() returns NULL
* Please use fwrite in binary mode to do this
* Make sure that you are setting node->next = NULL*/
void write_node(char * filename){
FILE* out = fopen(filename, "wb");
node* item = getLast();
while (item != NULL) {
item->next = NULL;
fwrite(item, sizeof(node), 1, out);
free(item);
item = NULL;
item = getLast();
}
fclose(out);
}