I am trying to learn C programming for a task at work and I have set myself a little project, which consists of reading down a file tree including all the sub directories obtaining information about each file.
The problem I couldn't solve is that how to make line when print all the directories as real tree command does.
and this is my sample code:
enum { doSkip, isFile, isDir } testDir(char *path, char *name)
{
struct stat st_buf;
if (strcmp(name, ".") == 0 || strcmp(name, "..") == 0) {
return doSkip;
}
stat(path, &st_buf);
if (S_ISDIR(st_buf.st_mode))
return isDir;
return isFile;
}
void list(const char *path, int indentlevel)
{
DIR *dirp = opendir(path);
struct dirent *dentry;
char buf[1024];
if (!dirp) {
printf("%*sNo access\n",indentlevel,"");
return;
}
while ((dentry = readdir(dirp)) != NULL) {
sprintf(buf,"%s/%s", path, dentry->d_name);
switch (testDir(buf,dentry->d_name)) {
case doSkip:
/* do nothing */
break;
case isDir:
printf("%*s%s:\n",indentlevel,"",dentry->d_name);
list(buf,indentlevel+4);
break;
case isFile:
printf("%*s%s\n",indentlevel,"",dentry->d_name);
break;
}
}
closedir(dirp);
}
int main()
{
list(".", 0);
return 0;
}
please give me some idea!
The insight you need is that printf doesn't have to print a full line. Unlike some other print functions in other languages.
Will do the trick.
You should change this to
list(buf,indentlevel+1)
because you are only going up one level. This way you can keep track of directory levels. Add another function to add extra spaces. See the example below:Here is a more complicated version, it stores data in a buffer, so it can find the last child in the folder and draw the correct "square edge" character for the last item. It still prints some extra vertical lines, that needs to be taken care of.