Skip to content

Instantly share code, notes, and snippets.

@ganapathichidambaram
Created May 3, 2020 13:21
Show Gist options
  • Save ganapathichidambaram/508daaa744c07bc3ea33bfd1d4aee9d5 to your computer and use it in GitHub Desktop.
Save ganapathichidambaram/508daaa744c07bc3ea33bfd1d4aee9d5 to your computer and use it in GitHub Desktop.
Listing filenames of huge number of file available in the Directory using C language
#define _GNU_SOURCE
#include <dirent.h> /* Defines DT_* constants */
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#define handle_error(msg) \
do { perror(msg); exit(EXIT_FAILURE); } while (0)
struct linux_dirent {
long d_ino;
off_t d_off;
unsigned short d_reclen;
char d_name[];
};
#define BUF_SIZE 1024*1024*5
void listdir(char * dname,char *otype,int inward) {
int fd, nread;
//char buf[BUF_SIZE];
char * buf = malloc(BUF_SIZE);
struct linux_dirent *d;
int bpos;
char d_type;
fd = open(dname != NULL ? dname : ".", O_RDONLY | O_DIRECTORY);
if (fd == -1)
handle_error("open");
for ( ; ; ) {
nread = syscall(SYS_getdents, fd, buf, BUF_SIZE);
if (nread == -1)
handle_error("getdents");
if (nread == 0)
break;
for (bpos = 0; bpos < nread;) {
d = (struct linux_dirent *) (buf + bpos);
d_type = *(buf + bpos + d->d_reclen - 1);
bpos += d->d_reclen;
if(d->d_ino && d->d_ino > 0 && strcmp(".",d->d_name)!=0 && strcmp("..",d->d_name)!=0 ) {
if( (d_type == DT_DIR || d_type == DT_LNK ) && ( strcmp("dirs",otype) ==0||strcmp("dirfiles",otype) ==0 ))
printf("%s/%s\n",dname,(char *) d->d_name);
else if(d_type == DT_REG && ( strcmp("files",otype) ==0 || strcmp("dirfiles",otype) ==0) )
printf("%s/%s\n",dname,(char *) d->d_name);
if( (d_type == DT_DIR || d_type == DT_LNK) && inward == 1 ) {
int dirname_len = strlen(dname);
char * subdir = calloc(1, PATH_MAX + 1);
strcat(subdir, dname);
strcat(subdir + dirname_len, "/");
strcat(subdir + dirname_len + 1, d->d_name);
listdir(subdir,otype,inward);
free(subdir);
}
}
}
}
close(fd);
free(buf);
}
int main (int argc, char *argv[]) {
int opt = 0;
char *dname = NULL;
char *otype = NULL;
int inward = 0;
while ((opt = getopt(argc, argv, "d:t:i:")) != -1) {
switch(opt) {
case 'd':
dname = optarg;
break;
case 't':
otype = optarg;
break;
case 'i':
inward = atoi(optarg) == 1 ? atoi(optarg) : 0;
//inward = atoi(optarg);
break;
case '?':
if (optopt == 'd')
dname =".";
else if (optopt == 't')
otype = "files";
else {
printf("\nInvalid option received\n");
return 1;
}
break;
}
}
listdir(dname,otype,inward);
exit(EXIT_SUCCESS);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment