#include #include #include typedef struct Dir_ Dir; typedef struct Dir_ { char name[32]; int size, dir; int children; Dir *parent; Dir *files[32]; } Dir; Dir* changeDir(Dir *dir, Dir *root, char *name) { printf("cd %s\n", name); if ( name[0] == '/' ) return root; if ( name[0] == '.' ) return dir->parent; for ( int i = 0; i < dir->children; i++ ) { if(strcmp( dir->files[i]->name, name ) == 0) { return dir->files[i]; } } } void list(Dir *dir, int d) { for (int i = 0; i < d; i++) printf("'-"); printf("%s", dir->name); if (dir->dir) printf(" (d)"); else printf(" %d", dir->size); printf("\n"); for (int i = 0; i < dir->children; i++) { list(dir->files[i], d+1); } } int findlarge(Dir *dir, int *globalsum) { if (!dir->dir) { return dir->size; } int sum = 0; for (int i = 0; i < dir->children; i++) { sum += findlarge(dir->files[i], globalsum); } if (sum <= 100000) { *globalsum += sum; } return sum; } int main() { char *line = 0; size_t len; ssize_t nlen; Dir *root = malloc(sizeof(Dir)); root->children = 0; root->dir = 1; strcpy(root->name, "/"); Dir *head = root; int globalsum = 0; while( (nlen = getline(&line, &len, stdin)) != -1 ) { line[nlen-1] = '\0'; if ( line[0] == '$' ) { if ( line[2] == 'c' ) head = changeDir(head, root, line+5); } else if ( line[0] == 'd' ) { Dir *newdir = malloc(sizeof(Dir)); strcpy(newdir->name, line+4); newdir->dir = 1; newdir->children = 0; newdir->parent = head; head->files[head->children] = newdir; head->children++; } else { Dir *newdir = malloc(sizeof(Dir)); newdir->size = atoi( strsep(&line, " ") ); strcpy(newdir->name, strsep(&line, " ")); head->files[head->children] = newdir; head->children++; // printf("file %d %s\n", newdir->size, newdir->name); // printf("name %s\n", root->files[0]->name); } printf("cmd '%s' head: %s\n", line, head->name); list(root, 0); } list(root, 0); findlarge(root, &globalsum); printf("sum: %d\n", globalsum); }