rendered paste body#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
#include <sys/stat.h>
#include <dirent.h>
char **get_files(char *, int *);
void err_exit(char *);
int
main(int argc, char *argv[]) {
char **file;
int j, nmr;
if(argc != 2) {
printf("Check your arguments\nExiting...\n");
exit(0);
}
file = get_files(argv[1], &nmr);
printf("Number of Files: %d\n\n", nmr);
for(j=0; j<nmr; j++) {
printf("%s\n", file[j]);
free(file[j]);
}
free(file);
exit(0);
}
char **get_files(char *tmp_path, int *num) {
char **buf;
int alloc_unit, i;
struct stat statbuf;
struct dirent *dirp;
DIR *dp;
alloc_unit = 0;
i = 0;
if( (buf = malloc(alloc_unit * sizeof(char *))) == NULL )
err_exit("malloc error");
alloc_unit = 2;
if( (dp = opendir(tmp_path)) == NULL ) {
err_exit("opendir error");
}
while ( (dirp = readdir(dp)) != NULL ) {
if( stat(dirp->d_name, &statbuf) < 0)
err_exit("stat error\n");
if (strcmp(dirp->d_name, ".") == 0)
continue; /* ignore current direcrory */
else {
++i;
if( i == (alloc_unit/2) ) { /* allocate more memory */
if( (buf = realloc(buf, alloc_unit * sizeof(char *))) == NULL)
err_exit("realloc error");
alloc_unit += alloc_unit;
}
if( (buf[i-1] = malloc(2+ strlen(dirp->d_name))) == NULL)
err_exit("malloc error");
strcpy(buf[i-1], dirp->d_name); /* store the name of file/dir */
if ( S_ISDIR(statbuf.st_mode) != 0 ) /* it's a directory, add '/' */
strcat(buf[i-1], "/");
}
}
*num = i;
return buf;
}
void err_exit(char *str) {
fprintf(stderr, str);
exit(1);
}