Grab file names and put in char array

Asked

Viewed 367 times

0

As I take the filenames of a directory and place 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;
}
  • First you need to decide whether to do it in C or C++, it looks like C, right? What problem are you having?

  • c++, but the above code is just c. Problem: I don’t know how to convert "drnt->d_name" to a multidimensional char array. I don’t even know which type is "drnt->d_name" and I don’t even know how to know the type of this variable. "drnt" is a struct and "d_name" is what? a char array?

1 answer

0


The structure dirent is definite 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. */
};

Like 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;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.