C programming - how does this recursive function work? For example, when the fun
ID: 3830074 • Letter: C
Question
C programming - how does this recursive function work?
For example, when the function gets full path name "/home/ysweng/hw/hw0/main.cpp" and passes it back to its parameter. The program should stop right?since "/home/ysweng/hw/hw0/main.cpp" is not a directory, it would return null when it tries to open. But instead it will still print out all of directories and its subdirectories and files such as hw1, hw2...
#include<stdio.h>
#include<dirent.h>
#include<sys/stat.h>
#include<string.h>
char *fullPath(char * dir, char * name)
{
char path[1024];
sprintf(path, "%s/%s", dir, name);
return strdup(path);
}
void listDir(char *name)
{
DIR *dir;
struct dirent *entry;
// printf("Testing: %s ", name);
if((dir = opendir(name)) != NULL)
{
while(entry = readdir(dir))
{
if(strcmp(entry->d_name,".") == 0 ||strcmp(entry->d_name, "..") == 0)
continue;
printf("%s ", fullPath(name, entry->d_name));
listDir(fullPath(name, entry->d_name));
}
}
}
int main(int argc, char *argv[])
{
if(argc == 1)
{
listDir(".");
}
else
listDir(argv[1]);
return 0;
}
main /home/ysweng/hw /home/ysweng/hw/ hw0 /home ysweng/hw/hw0/create script /home ysweng/hw/hw0 /main cpp /home/ysweng/hw/hw0 /Makefile /home ysweng/hw/hw0 /main. txt /home ysweng/hw/hw0/main /home /ysweng/hw/hw1 /home/ysweng/hw/ hw1/hw1_1 /home/ysweng/hw/ hw1/hw1_1/a out /home/ysweng/hw/ hw1/hw1 1/main.cpp home /ysweng/hw/ hw1/hw1_2 /home /ysweng/hw/ hw1/hw1_2/a outExplanation / Answer
Hi, I have commented each line.
Please read comments and let me know in case of any issue.
#include<stdio.h>
#include<dirent.h>
#include<sys/stat.h>
#include<string.h>
// this function returns the absolute(full) path of a file
char *fullPath(char * dir, char * name)
{
char path[1024];
sprintf(path, "%s/%s", dir, name);
return strdup(path);
}
// function to read all files in directory: name
void listDir(char *name)
{
DIR *dir;
struct dirent *entry;
// printf("Testing: %s ", name);
if((dir = opendir(name)) != NULL) // reading current directory content
{
while(entry = readdir(dir)) // traversing each file(entry) of current directory
{
// if current read directory entry(files or directory)
//is hedden the do not print or travese
if(strcmp(entry->d_name,".") == 0 ||strcmp(entry->d_name, "..") == 0)
continue;
// rprinting full path of current entry(file)
printf("%s ", fullPath(name, entry->d_name));
// if current entry is a type of directory, then
// recursively call listDir for this directory
listDir(fullPath(name, entry->d_name));
}
}
}
int main(int argc, char *argv[])
{
if(argc == 1)
{
listDir(".");
}
else
listDir(argv[1]);
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.