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;
}
Why not use
scandir
to provide the array for you, rather than iterating through the entries?This seems to work for me:
Gives me: