Search code examples
carraysfile-listing

save file listing into array or something else C


I have this function

void file_listing(){
    DIR *dp;
    struct stat fileStat;
    struct dirent *ep;
    int file=0;
    dp = opendir ("./");

    if (dp != NULL){
        while ((ep = readdir(dp))){
            char *c = ep->d_name;
            char d = *c; /* first char */
            if((file=open(ep->d_name,O_RDONLY)) < -1){ 
                perror("Errore apertura file");
            }
            if(fstat(file,&fileStat)){ /*file info */
                perror("Errore funzione fstat");
            }
            if(S_ISDIR(fileStat.st_mode)){ /* directory NOT listed */
                continue;
            }
            else{
                if(d != '.'){ /* if filename DOESN'T start with . will be listed */
                    "save into someting" (ep->d_name);
                }
                else{
                    continue; /* altrimenti non lo listo */
                }
            }
        }
        (void) closedir (dp);
    }
    else{
        perror ("Impossibile aprire la directory");
        return 1;
    }
}

I want to save into an array or a struct or a list or something else the result of file listing but i don't know how to do it.
Thanks in advance!


Solution

  • Here is a sample function that stores the file listing in array and returns the number of entries:

    #include <string.h>
    #include <stdio.h>
    #include <dirent.h>
    #include <malloc.h>
    
    size_t file_list(const char *path, char ***ls) {
        size_t count = 0;
        size_t length = 0;
        DIR *dp = NULL;
        struct dirent *ep = NULL;
    
        dp = opendir(path);
        if(NULL == dp) {
            fprintf(stderr, "no such directory: '%s'", path);
            return 0;
        }
    
        *ls = NULL;
        ep = readdir(dp);
        while(NULL != ep){
            count++;
            ep = readdir(dp);
        }
    
        rewinddir(dp);
        *ls = calloc(count, sizeof(char *));
    
        count = 0;
        ep = readdir(dp);
        while(NULL != ep){
            (*ls)[count++] = strdup(ep->d_name);
            ep = readdir(dp);
        }
    
        closedir(dp);
        return count;
    }
    
    int main(int argc, char **argv) {
    
        char **files;
        size_t count;
        int i;
    
        count = file_list("/home/rgerganov", &files);
        for (i = 0; i < count; i++) {
            printf("%s\n", files[i]);
        }
    }
    

    Note that I iterate twice over the directory - first time to get the files count and second time to save the results. This won't work correctly if you add/remove files in the directory while this is being executed.