c programming - can anyone explain to me how does the following code work recurs
ID: 3825122 • Letter: C
Question
c programming - can anyone explain to me how does the following code work recursively? I highlighted the parts that I don't quit understand.
The code should be able to print out all of directory and its subdirectories recursively
#include <stdio.h>
#include<string.h>
void listdir(const char *name)
{
DIR *dir;
struct dirent *entry;
if (!(dir = opendir(name)))
return;
if (!(entry = readdir(dir)))
return;
do {
if (entry->d_type == DT_DIR) {
char path[1024];
int len = snprintf(path, sizeof(path)-1, "%s/%s", name, entry->d_name);
path[len] = 0;
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
continue;
printf("%s/%s ", name, entry->d_name);
listdir(path);
}
else
printf("%s/%s ",name, entry->d_name);
} while (entry = readdir(dir));
closedir(dir);
}
Explanation / Answer
#include <stdio.h>
#include<string.h>
void listdir(const char *name)
{
DIR *dir;
// Pointer for directory entry
struct dirent *entry;
// opendir returns NULL if couldn't open directory
if (!(dir = opendir(name)))
return;
if (!(entry = readdir(dir)))
return;
do {
if (entry->d_type == DT_DIR) {
char path[1024];
// checking lenagainst negative value
int len = snprintf(path, sizeof(path)-1, "%s/%s", name, entry->d_name);
// path of length 0
path[len] = 0;
// returns FALSE if the current entry is the current directory (.) and the directory above this (..)
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
continue;
printf("%s/%s ", name, entry->d_name);
// returns a list containing the names of the entries in the directory given by path.
listdir(path);
}
else
printf("%s/%s ",name, entry->d_name);
} while (entry = readdir(dir));
closedir(dir);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.