/* ndistinct.c from CS360 midterm exam on 3/9/2021. */ #include #include #include #include #include #include "jrb.h" /* Since inodes are longs, you need to write your own comparison function. */ int compare(Jval v1, Jval v2) { if (v1.l < v2.l) return -1; if (v1.l > v2.l) return 1; return 0; } /* Use opendir() / readdir() to enumerate files. Use stat to find each files' inode number. Store the inodes in a red-black tree so that you can discover duplicates. */ int main() { JRB tree; /* The tree. */ DIR *d; /* The open directory. */ struct dirent *de; /* Each file in the directory. */ struct stat buf; /* The file's metadata. */ int ndistinct; /* The number of distinct files. */ /* Do initialization */ tree = make_jrb(); d = opendir("."); if (d == NULL) { perror("."); exit(1); } ndistinct = 0; /* Enumerate the files and look up each inode in the tree. Only insert an inode if it's not there already. */ for (de = readdir(d); de != NULL; de = readdir(d)) { if (stat(de->d_name, &buf) != 0) { perror(de->d_name); exit(1); } if (jrb_find_gen(tree, new_jval_l(buf.st_ino), compare) == NULL) { ndistinct++; jrb_insert_gen(tree, new_jval_l(buf.st_ino), new_jval_i(0), compare); } } /* Print the final answer. I don't close the directory or free the tree, because that is done automatically when the program ends. */ printf("%d\n", ndistinct); return 0; }