I'm a Java dev and I'm learning C. I'm working on a project, it's the implementation of tree command from linux in C and I have a simple question. Is this t_node a linked list? It looks like a linked list for me.
This is a part of the code:
struct t_node {
char* name;
int ptd;
struct t_node *next_dfile;
struct t_node *next_file;
};
static struct t_node* create_tree(char *root_name) {
DIR *dir = opendir(root_name);
struct dirent *dr = {NULL};
struct t_node *ptr_tstart = NULL,*temp = NULL,*temp1 = NULL;
char *name = (char *)calloc(2000, sizeof(char));
if (dir == NULL) {
printf("\nFailed to open ..!!");
printf(" : %s", root_name);
return NULL;
}
while ((dr = readdir(dir)) != NULL) {
if (strcmp((dr->d_name), ".") != 0 && strcmp((dr->d_name), "..") != 0) {
temp = create_tnode(dr->d_name);
} else {
temp = NULL;
continue;
}
if (temp1 != NULL) {
temp1->next_file = temp;
} else {
(ptr_tstart) = temp;
}
if ((dr->d_type) == DT_DIR) {
temp->ptd = TRUE;
strcpy(name, root_name);
(temp->next_dfile) = create_tree((strcat((strcat(name, "/")), dr->d_name)));
strcpy(name, root_name);
} else {
(temp)->ptd = FALSE;
(temp)->next_dfile = NULL;
}
temp1 = temp;
}
return (ptr_tstart);
}
static struct t_node* create_tnode(char* n) {
struct t_node *temp = (struct t_node *)malloc(sizeof(struct t_node));
temp->name = n;
temp->next_dfile = NULL;
temp->next_file = NULL;
return temp;
}
t_node will be a file or directory, if ptd is true then it is a directory. next_file will be the next file/directory in the same directory and next_dfile will be the next file/folder inside a directory.
We have music_dir with rock and disco files and movie_dir with drama and thriller files. mudic_dir will have movie_dir as next_file. And music_dir will have rock as next_dfile, and rock will have disco as next_file, etc.
I just want to know if this t_node is a linked list. Thank you!
CodePudding user response:
It's a tree.
The pointers to the siblings are stored in a linked-list. But overall, you have a tree.
|
v
--- --- ---
| |->| |->| |
--- --- ---
| | |
----------- | ----------------
| | |
v v v
--- --- --- --- --- --- --- --- ---
| |->| |->| | | |->| |->| | | |->| |->| |
--- --- --- --- --- --- --- --- ---
| |
-------- -------
| |
v v
--- --- --- --- --- ---
| |->| |->| | | |->| |->| |
--- --- --- --- --- ---