Skip to content

Instantly share code, notes, and snippets.

@lstipakov
Created July 20, 2016 15:56
Show Gist options
  • Save lstipakov/dfcdc264490132b12cf769f01438f484 to your computer and use it in GitHub Desktop.
Save lstipakov/dfcdc264490132b12cf769f01438f484 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#include <fcntl.h>
#include <errno.h>
#include <memory.h>
#include <linux/limits.h>
#include <sys/wait.h>
void fill_attrs(char* attrs, mode_t mode) {
if (S_ISDIR(mode)) {
attrs[0] = 'd';
}
if (S_IRUSR & mode) {
attrs[1] = 'r';
}
if (S_IWUSR & mode) {
attrs[2] = 'w';
}
if (S_IXUSR & mode) {
attrs[3] = 'x';
}
if (S_IRGRP & mode) {
attrs[4] = 'r';
}
if (S_IWGRP & mode) {
attrs[5] = 'w';
}
if (S_IXGRP & mode) {
attrs[6] = 'x';
}
if (S_IROTH & mode) {
attrs[7] = 'r';
}
if (S_IWOTH & mode) {
attrs[8] = 'w';
}
if (S_IXOTH & mode) {
attrs[9] = 'x';
}
}
void processDir(const char* d) {
DIR* dir = NULL;
chdir(d);
dir = opendir("./");
/*
char newdir[PATH_MAX];
strcpy(newdir, "./");
strcat(newdir, d);
dir = opendir(newdir);
printf("\npid %d, dir %s\n", getpid(), newdir);
*/
if (dir == NULL) {
printf("Cannot open directory %s, err: %d\n", d, errno);
return;
}
struct dirent* ent = NULL;
struct stat st;
char attrs[11]; // drwxrwxrwx
while ((ent = readdir(dir)) != NULL) {
strcpy(attrs, "----------");
lstat(ent->d_name, &st);
fill_attrs(attrs, st.st_mode);
printf("%s %10ld %s", attrs, st.st_size, ent->d_name);
if (S_ISLNK(st.st_mode)) {
char buf[PATH_MAX + 1];
readlink(ent->d_name, buf, PATH_MAX + 1);
struct stat st1;
if (stat(buf, &st1) == -1) {
printf(" symlink broken");
} else {
printf(" symlink");
}
}
if ((S_ISDIR(st.st_mode) != 0) &&
(strncmp(ent->d_name, ".", 1) != 0) &&
(strncmp(ent->d_name, "..", 2) != 0)) {
if (fork() == 0) {
// child
processDir(ent->d_name);
break;
} else {
//printf("\nDir: %s\n", ent->d_name);
int status;
wait(&status);
//break;
}
}
printf("\n");
}
}
int main(int argc, char const *argv[]) {
printf("My pid %d\n", getpid());
if (argc > 1) {
processDir(argv[1]);
} else {
processDir(".");
}
printf("\n\n\n\n\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment