/****************************************************************************
*	LISTNLMS.C
*	Illustrate linked list traversal with NetWare internal debugger
*  Builds list of NLMs in SYS:SYSTEM
*
*	Morgan Adair
*	7/11/91
****************************************************************************/

#include <stdio.h>
#include <nwdir.h>
#include <string.h>
#include <malloc.h>
#include <conio.h>
#include <errno.h>

typedef struct filename {
	char	fname[NAME_MAX+1];	/* 12 + 1 bytes */
	struct filename	*next;
} FILE_NAME;

void CleanUp(void);

DIR	*sysSystem;
FILE_NAME	*fileList = NULL;

void main(void)
{
	DIR			*dirEntry;
	FILE_NAME	*newNode;
	int			numFiles = 0;

	atexit(CleanUp);

	sysSystem = opendir("SYS:SYSTEM\\*.NLM");

	if (!sysSystem) {
		printf("Unable to open SYS:SYSTEM");
		exit();
	}

	/* just for fun, break into the debugger here */
	Breakpoint(1);

	do {	/* while getting directory entries */
		dirEntry = readdir(sysSystem);
		if (dirEntry) {
		 	newNode = (FILE_NAME *)malloc(sizeof(FILE_NAME));
			if (!newNode) {
			 		printf("Out of memory");
					exit();
			}
			numFiles++;
			strcpy(newNode->fname, dirEntry->d_name);
			newNode->next = fileList;
			fileList = newNode;
			/* display file name, just to keep up the appearance that
			   we're doing something useful (maybe if we sorted the
				file names alphabetically . . .) */
			printf("%-20s", newNode->fname);
		}
	} while (dirEntry);

	Breakpoint(2);
}

void CleanUp(void)
{
	FILE_NAME	*newNode;

	closedir(sysSystem);

	while (fileList) {
	 	newNode = fileList;
		fileList = fileList->next;
		free(newNode);
	}
}
