All pastes #1805361 Raw Edit

tutor 4 sol

public c v1 · immutable
#1805361 ·published 2010-02-22 03:33 UTC
rendered paste body
/* t8.c : command line call using "t8 t8tape t8cmd" *//* */#include <stdio.h>#include <stdlib.h>/* This program implements a doubly-linked list with* no head or tail nodes. It reads in a string from* "tapefile", then allows you to go left and right* along that string depending on whether "commandfile"* says '<' or '>'. */struct LLNode{char key;struct LLNode *left;struct LLNode *right;};struct LLNode *list = NULL;struct LLNode *insertLL(struct LLNode *, char);struct LLNode *rewindLL(struct LLNode *);struct LLNode *printNmoveLL(struct LLNode *, char);int main(int argc, char *argv[]){	FILE *fin;	int i, c;	if (argc != 3){		fprintf(stderr,"Usage: %s <tapefile> <commandfile>\n",argv[0]);		return(1);	}/* Read the tape file */fin = fopen(argv[1],"r");if (fin==NULL){	perror("opening tapefile");	return(2);}i = 0;do{	c=fgetc(fin);	if(c!=EOF)		list=insertLL(list,c);} while(c!=EOF);if (fclose(fin)){	perror("closing tapefile");	return(3);}list = rewindLL(list);/* Read commandfile and follow its instructions */fin = fopen(argv[2],"r");if (fin==NULL){	perror("opening commandfile");	return(4);}do{	c=fgetc(fin);	list=printNmoveLL(list,c);} while(c!=EOF);putchar('\n');if(fclose(fin)){	perror("closing commandfile");	return(5);}return(0);}struct LLNode *rewindLL(struct LLNode *list){/* Rewind the list to the beginning (leftmost end) */if (list!=NULL){ /* in case the list is empty */	while (list->left) /* not yet at the leftmost node */		list = list->left; /* so, go left */}return(list);}struct LLNode *printNmoveLL(struct LLNode *list, char dir){/* Print the character at the current list position, then* move it according to the direction indicated in dir. If* we're at the edge then don't move. */if(dir==EOF || isspace(dir))return(list);putchar(list->key);switch (dir){	case '>':	if (list->right) /* can move right */		list = list -> right;	else		printf("\nError: no more space on right\n");	break;	case '<':	if (list->left) /* can move left */		list = list -> left;	else		printf("\nError: no more space on left\n");	break;		default:		printf("\nError: unknown command '%c'\n",dir);}return(list);}struct LLNode *insertLL(struct LLNode *list, char c){struct LLNode *new;new=(struct LLNode *)malloc(sizeof(struct LLNode));new->key = c;if (list){new->right=list->right;new->left=list;list->right=new;if (new->right)	new->right->left=new;}else new -> right = new -> left = NULL;return (new);}