Home > Back-end >  How to read all files in the directory and store them in the pointer in the C language program?
How to read all files in the directory and store them in the pointer in the C language program?

Time:10-12

Mingw x86_64 v11.2.0
Windows 10 21H2

My current problem is that this function can normally read files and folders in the directory, but if it is saved in the pointer and printed on the screen, a single file will appear repeatedly.

These are the files in the directory.

.
..
main.c
main.exe
README.md
test.txt

The following is the source code I wrote:

#include "../DeleteCompletely.h"
#include <dirent.h>

#define TotalNumber      4096
#define TotalFileNameLen 4096

typedef struct dirent DIRENT;

typedef struct {
    DIR    *dir_ptr;
    DIRENT *dirent_ptr;
    char  **pathSet;
    size_t  number;
} snDIR;

static snDIR *getAllFile(const char *path)
{
    snDIR *dirSet = (snDIR *)malloc(sizeof(snDIR));
    dirSet->dir_ptr = opendir(path);
    size_t loopIndex;

    dirSet->pathSet = (char **)malloc(sizeof(char **) * TotalNumber);
    if(dirSet->dir_ptr) {
        dirSet->number = 0;
        loopIndex = 0;
        while ((dirSet->dirent_ptr = readdir(dirSet->dir_ptr)) != NULL) {
            dirSet->pathSet[loopIndex] = (char *)malloc(TotalFileNameLen);
            dirSet->pathSet[loopIndex] = dirSet->dirent_ptr->d_name;

            dirSet->number  ;
            loopIndex  ;
        }
        closedir(dirSet->dir_ptr);
    }

    return dirSet;
}

int main(int argc, char **argv)
{
    snDIR *set = getAllFile(".");

    for(size_t x = 0; x < set->number;   x) {
        printf("%s\n", set->pathSet[x]);
    }

    free(set);
    return 0;
}

CodePudding user response:

The problem are these assignments:

dirSet->pathSet[loopIndex] = (char *)malloc(TotalFileNameLen);
dirSet->pathSet[loopIndex] = dirSet->dirent_ptr->d_name;

The first make dirSet->pathSet[loopIndex] point to one location. The second make it point somewhere completely different.

Instead of the second assignment you need to copy the string:

strcpy(dirSet->pathSet[loopIndex], dirSet->dirent_ptr->d_name);

You're also wasting quite a lot of memory by always allocating a large amount or memory. The likelihood of the string being that large are rather small. Instead use the string length as the base size:

dirSet->pathSet[loopIndex] = malloc(strlen(dirSet->dirent_ptr->d_name)   1);
//  1 for the null terminator
  • Related