xiaofan2406
xiaofan2406

Reputation: 3310

c: return all the filenames in directory

How to writte a function that is to return all the file names in a directory including files in the sub directories. So far, I have something like this, but it doesn't work right, I try call this function and print out each element, it only prints the first element.

Can anyone tell me what I do wrong or the other approach of writing this function?

char **allFiles(char *dir, OPTIONS opts) {
        char **allfiles = malloc(sizeof(char **));
        struct dirent *dp;

        while((dp = readdir(dirp)) != NULL) {

            if (strcmp(dp->d_name, ".") == 0 || strcmp(dp->d_name, "..") == 0)
                continue;
            if (dp->d_type == DT_DIR)
                allfiles = allFiles(strcat(strcat(dir, "/"), dp->d_name));

            if (dp->d_type != DT_DIR)
                *allfiles = strdup(strcat(strcat(strdup(dir), "/"), dp->d_name));

            ++allfiles;
        }
    closedir(dirp);
    return allfiles;
}

Upvotes: 1

Views: 1824

Answers (3)

wildplasser
wildplasser

Reputation: 44250

The allfiles[] array is filled by both the parent and the recursive child. The child inserts into it, but the results are overwitten by the parent.

UPDATE: after rereading, I see the array management looks Ok (besides possibly overrunning it's end) Maybe you run out of file descriptors ?

UPDATE2: replace

if (dp->d_type != DT_DIR)
        *allfiles = strdup(strcat(strcat(strdup(dir), "/"), dp->d_name));
        ++allfiles;

By:

if (dp->d_type != DT_DIR)
        *allfiles++ = strdup(strcat(strcat(strdup(dir), "/"), dp->d_name));

Upvotes: 2

Michel
Michel

Reputation: 2623

Increasing the allfiles pointer cannot be done because you only allocated room to hold 1 pointer (to a char *). Another issue is that allfiles is overwritten when a directory is found (thus loosing all the previous found files and directories).

Upvotes: 0

Michael Krelin - hacker
Michael Krelin - hacker

Reputation: 143259

Have you considered using glob() if your platform has it?

Upvotes: 0

Related Questions