How to insert ep->d_name into an array in C

1.4k views Asked by At

I've got the following code that lists all files in a directory. I'm trying to add each ep->d_name into an array but so far all I've tried has not worked. How should I proceed?

#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <unistd.h> 
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <time.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/times.h>
#include <sys/wait.h>

int main (void){
    DIR *dp;
    struct dirent *ep;
    dp = opendir("./");
    int count = 0;

    char *fileNames = calloc(256, sizeof(char));

    if(dp != NULL){
        while(ep = readdir(dp)){
            printf("%s\n", ep->d_name);  
            count = count+1;
        }
        for (int i=0; i<count; i++){
        fileNames[i] = ep->d_name;
        }
        closedir(dp);
     }else{
         perror("Couldn't open the directory");
     }
     return 0;
 }

This bit of code must remain unchanged:

int main (void){

    DIR *dp;
    struct dirent *ep;
    dp = opendir("./");

    if(dp != NULL){
        while(ep = readdir(dp)){
            printf("%s\n", ep->d_name);
        }
        closedir(dp);
    }else{
        perror("Couldn't open the directory");
    }
    return 0;

}
1

There are 1 answers

1
erik258 On

Why not use scandir to provide the array for you, rather than iterating through the entries?

This seems to work for me:

$ cat t.c
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <time.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/times.h>
#include <sys/wait.h>

int main (void){
    DIR *dp;
    struct dirent **list;

    int count = scandir("./", &list, NULL, alphasort );
     if( count < 0 ){
         perror("Couldn't open the directory");
         exit(1);
     }
    printf("%u items in directory\n", count);
    for( int i=0; i<count;i++){
            printf("%s\n", list[i]->d_name);
     }
     return 0;
 }

Gives me:

docker run -it --rm -v `pwd`/t.c:/t.c gcc bash -c "gcc -o t t.c && ./t"
24 items in directory
.
..
.dockerenv
bin
boot
dev
etc
home
lib
lib64
media
mnt
opt
proc
root
run
sbin
srv
sys
t
t.c
tmp
usr
var