Get filenames and put char array

0

How do I get the names of the files in a directory and put them in a multidimensional char array?

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

int main()
{
    char arrayNomes[10][50];
    char dirn[50];
    DIR *dir = NULL;
    struct dirent *drnt = NULL;

    dir = opendir(dirn);
    if (dir)
    {
        while (drnt = readdir(dir))
        {
            printf("%s\n", drnt->d_name);
            //Como fazer algo como isso abaixo:
            for (...)
            {
                arrayNomes[i] = drnt->d_name;
            }
        }
        closedir(dir);
    }
    else
    {
        printf("Can not open directory '%s'\n", dirn);
    }

    return 0;
}
    
asked by anonymous 24.06.2017 / 21:11

1 answer

0

The dirent structure is defined in dirent.h as

struct dirent
{
    long            d_ino;      /* Sempre zero. */
    unsigned short  d_reclen;       /* Sempre sizeof struct dirent. */
    unsigned short  d_namlen;       /* Tamanho do nome em d_name. */
    unsigned        d_type;     /* Atributos to arquivo. */
    char            d_name[FILENAME_MAX]; /* Nome do arquivo. */
};

Since dirent.d_name is an array of char, you can do so

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

#define MAX_ARRAY_NOMES  10
#define MAX_NOME_ARQUIVO 255

int main()
{
    int i = 0;
    char arrayNomes[MAX_ARRAY_NOMES][MAX_NOME_ARQUIVO];
    char dirn[] = { "diretorio_exemplo" };
    DIR *dir = NULL;
    struct dirent *drnt = NULL;

    dir = opendir(dirn);
    if (dir)
    {
        while (drnt = readdir(dir))
        {
            strcpy(arrayNomes[i++], drnt->d_name);
            if (i == MAX_ARRAY_NOMES)
            {
                break;
            }
        }
        closedir(dir);

        for (i = 0; i < MAX_ARRAY_NOMES; i++)
        {
            printf("[%d]: %s\n", i, arrayNomes[i]);
        }
    }
    else
    {
        printf("Can not open directory '%s'\n", dirn);
    }

    return 0;
}
    
25.06.2017 / 00:18