-1

I am trying to scan all files in my computer, including files in subdirectories. The program should start in the root folder "/".

logfind.c

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <pwd.h>
#include <stdlib.h>:
#include <dirent.h>

int is_directory(const char *path) {
        struct stat path_stat;
        stat(path, &path_stat);
        return S_ISDIR(path_stat.st_mode);
}

void list_files(char *pathus) {
        struct dirent *de;

        DIR *dr = opendir(pathus);

        if (dr == NULL) {
                printf("Could not open current directory");
                exit(1);
        }

        while ((de = readdir(dr)) != NULL) {
                if (is_directory(de->d_name) > 0)
                        list_files(de->d_name);
                else
                        printf("%s\n", de->d_name);
        }

        closedir(dr);
}

int main(int argc, char **argv) {
        list_files("/");
        return 0;
}

The output I get when running this is basically "logfind.c" many times, anyone has an idea as to why this happens?

  • 1
    You have to skip names like .. and . when `de->d_name` `.` and `..` – Seek Addo Jun 27 '17 at 12:53
  • First a little unrelated FYI: The `dirent` structure already contain a type, that can be used to see if an entry is a directory or not, no need for a `stat` call. Then for the main part: The name in `d_name` is not the full path. You need to append it to the current path in `pathus`. – Some programmer dude Jun 27 '17 at 12:54
  • 3
    If you want to save you some trouble, take a look at `man 3 ftw` – Ctx Jun 27 '17 at 12:57
  • Make sure you check the return value of `stat` before you access `path_stat.st_mode` – Seek Addo Jun 27 '17 at 12:57
  • remove `exit(1);` in the `dr ==NULL` if clauses, if you get a permission denied error, it should report the error and move on to the next file or directory. One thing. don't ever report errors to stdout with printf, use `fprintf` – Seek Addo Jun 27 '17 at 14:12
  • How do I tell it to move on to the next file? – Danny Damsky Jun 27 '17 at 14:15

1 Answers1

2

This happens because there's nothing in your code to change the process' current directory, or build the full path of the directory to scan.

If you're in /home/danny/src/ when you run this, and find dev while listing /, you can't opendir("dev"), that'd mean /home/danny/src/dev, not /dev.

unwind
  • 391,730
  • 64
  • 469
  • 606