/* The code must be recursive, since this is a directory traversal */ void find_txt_files(char *directory, JRB lines) { DIR *d; /* Directory pointer */ struct dirent *de; /* Directory entry */ char *path; /* Path name that must be constructed for each file */ Dllist dirs, tmp; /* List of directories to traverse */ struct stat buf; /* Stat buffer to check for directories */ IS is; /* Inputstruct to read the first line of a file */ /* First preallocate space for the constructed pathname */ path = (char *) malloc(sizeof(char)*(strlen(directory)+258)); if (path == NULL) { perror("malloc"); exit(1); } /* Open the directory, and create the list of subdirectories */ d = opendir(directory); if (d == NULL) { perror(directory); exit(1); } dirs = new_dllist(); /* Traverse the directory */ for (de = readdir(d); de != NULL; de = readdir(d)) { /* Construct the file name, then test to see if it is a subdirectory that must be traversed -- remember to ignore . and .. */ sprintf(path, "%s/%s", directory, de->d_name); if (lstat(path, &buf) == 0 && strcmp(de->d_name, ".") != 0 && strcmp(de->d_name, "..") != 0) { if (S_ISDIR(buf.st_mode)) { dll_append(dirs, new_jval_s(strdup(path))); } } /* If the file ends with .txt, then read its first line and put it into the red black tree. */ if (strlen(path) >= 4 && strcmp(".txt", path+(strlen(path)-4)) == 0) { is = new_inputstruct(path); if (is != NULL) { if (get_line(is) >= 0) { jrb_insert_str(lines, strdup(is->text1), new_jval_v(NULL)); } jettison_inputstruct(is); } } } /* Close the directory and traverse subdirectories */ closedir(d); dll_traverse(tmp, dirs) find_txt_files(tmp->val.s, lines); /* Free up memory -- the directory names, the list, path */ dll_traverse(tmp, dirs) free(tmp->val.s); free_dllist(dirs); free(path); return; } /* The main routine -- create the red black tree, make the first recursive call to find_txt_files, traverse the tree and print out the first lines */ main() { JRB lines, tmp; lines = make_jrb(); find_txt_files(".", lines); jrb_traverse(tmp, lines) printf("%s", tmp->key.s); }

Question 2: Grading