Home > OS >  How to save list of directory in global Array in C?
How to save list of directory in global Array in C?

Time:09-05

I have this code that print list of directory.

How to save that list of directory in global array and print that global array from main function ?

#include <stdio.h>
#include <dirent.h>
 

void listFiles(const char* dirname)
{
    DIR* dir = opendir(dirname);
    if(dir == NULL)
    {
        return ;  
    }
    struct dirent* entity ;
    entity = readdir(dir);
     
     while(entity != NULL)
    {   
        printf("%s\n", entity->d_name);
        entity = readdir(dir);

    }
    
    closedir(dir);
    
    return;
}   

int main()
{
    listFiles(".");

return 0;
}

CodePudding user response:

Using global variables is a terrible habit. Also declaring functions as void if they should return something meaningful. In your case dynamically allocate the array and return it to the caller. Also try to reduce the number of return points in the function (ideally only one) by using positive checks instead of negative ones.

struct dirent *listFiles(const char* dirname, size_t *size)
{
    struct dirent *entity, *result = NULL;
    DIR* dir = NULL;

    if(size) 
    {
        dir = opendir(dirname);
        *size = 0;
    }
    if(dir)
    { 
        while((entity = readdir(dir)))
        {   
            struct dirent *tmp;
            tmp = realloc(result, sizeof(*result) * (*size   1));
            if(!tmp) {/* error handling */ }
            else
            {
                result = tmp;
                memcpy(result   *size, entity, sizeof(*result));
                *size  = 1;
            }
        }
        closedir(dir);
    }
    return result;
}   

int main(void)
{
    size_t size;
    struct dirent *dir = listFiles(".", &size);
    if(size && dir)
    {
        for(size_t x = 0; x < size; x  )
        {
             printf("%s\n", dir[x].d_name);
        }
    }
    free(dir);
}

https://godbolt.org/z/PPTcsd4E8

Instead memcpy you can also assign the structures:

result[*size] = *entity;
  •  Tags:  
  • c
  • Related