简体   繁体   中英

Why is my program not displaying any output?

I am trying to recursively traverse through a directory and list any files that end in .txt or the names of folders.

void listFilesRecursively(char *basePath) {

    char path[1000];
    struct dirent *ptr;
    DIR *dir = opendir(basePath);

    // Unable to open directory
    if (!dir)
        return;

    while ((ptr = readdir(dir)) != NULL) 
    {
        if (strcmp(ptr->d_name,".") != 0 && strcmp(ptr->d_name, "..") != 0)
        {

            char *name = NULL;
            char *type = NULL;

            while (name != "." || name != NULL) {
                name++;
            }

            for (name = ptr->d_name; *name != '\0' ; name++) {

                if (name == '.') {
                    while (*name != '\0') {
                        *type = *name;
                        name++;
                    }
                        break;                      

                } else if (*name == '\0') {
                    printf("%s\n", ptr->d_name);
                }

            }                   

            if (strcmp(type,"txt") == 0)            
                printf("%s\n", ptr->d_name);

            // create new path from our base path
            strcpy(path, basePath);
            strcat(path, "/");
            strcat(path, ptr->d_name);

            listFilesRecursively(path);

        }
    }
        closedir(dir);
}

My expected results would be the files that end in .txt and files that are folders. However, the output is blank and it may go into an infinite loop.

This is an infinite loop:

        while (name != "." || name != NULL) {
            name++;
        }

name is a char* . Unless the interned string literal "." is stored at the NULL address (it isn't), then you're saying the loop should continue forever, because name will always be either not pointing to the storage for "." or not pointing to NULL . While I believe it's officially undefined behavior to compare unrelated pointers like "." and name , in practice most (all flat memory model?) compilers just allow arbitrary pointer comparisons, and since you never dereference the pointer, you never actually try to read the unallocated addresses you're traversing (you'd eventually segfault if you did), so it just goes on forever.

I'm unclear on what the goal of that loop is (maybe stripping leading . s from "hidden" file names?), so I can't really suggest a fix other than removing it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM