Question

I'm trying to display all the files and sub directories in a windows path using the dirent.h and this is my code so far:

void print_dir(char* path, char* subdir)
{
    char full_path[MAX_PATH];

    concat_path(full_path, path, subdir);

    DIR *dir;
    struct dirent *ent;

    if ((dir = opendir (full_path)) != NULL) {
        /* print all the files and directories within directory */
        while ((ent = readdir(dir)) != NULL) {
            if(is_dir(full_path, ent->d_name)){
                printf ("DIR %s\\%s\n",full_path, ent->d_name);
                print_dir(full_path, ent->d_name);
            }
            else{
                printf ("%s\\%s\n",full_path, ent->d_name);
            }
        }
        closedir (dir);
    } else {
        /* could not open directory */
        perror ("");
    }
}

I'm trying it on a directory D:\test which has two sub directories with a file in each of them and the function is getting stuck in an infinite recursion and displays \.\.\.\.\.\. infinitely. If i put a condition to check if the name is "." or ".." and if it is to not do anything, it all works as planned. So what are these dots?

Was it helpful?

Solution

These dots are directories or at least links to directories: every directory contains at least two subdirectories: "." and "..": the "." directory points the current directory itself and the ".." directory points to the parent directory. On windows both directories are not visible in the explorer but you can show them by using the command prompt and enter "dir". BTW: on linux systems you can display them by entering "ls -a" in nearly any shell.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top