0

I'm stuck on unix system programming and am beginner about it. Assume that there is a directory which is X. There are a file(text1.txt) and another directory which is Y in X. Last, there are two files(text2.noExtension) and text3.noExtension) and another directory which is Z in Y. My goal is that read files and enter directories until there is no directory. Candidly, I really don't have any idea how to go on.

#include <dirent.h>
#include <errno.h>
#include <stdio.h>
int main(int argc, char *argv[]) {
    struct dirent *direntp;
    DIR *dirp;
    if (argc != 2) {
        fprintf(stderr, "Usage: %s directory_name\n", argv[0]);
        return 1; }
    if ((dirp = opendir(argv[1])) == NULL) 
    {
        perror ("Failed to open directory");
        return 1;
    }
    while ((direntp = readdir(dirp)) != NULL)
        printf("%s\n", direntp->d_name);
    while ((closedir(dirp) == -1) && (errno == EINTR)) ;
    return 0; 
}
  • There are definitely other questions on SO that tackle the problem you outline, and deal with problems encountered. I'll try to find them; so should you. – Jonathan Leffler Mar 24 '15 at 20:09
  • 1
    [How can I get the list of files in a directory](http://stackoverflow.com/questions/612097); see also [`stat()` error: no such file or directory when file name is returned by `readdir()`](http://stackoverflow.com/questions/5125919). And others, no doubt. – Jonathan Leffler Mar 24 '15 at 20:15
  • 1
    There really isn't a need to loop on `closedir()`. – Jonathan Leffler Mar 24 '15 at 20:30

1 Answers1

1

If you want to list all directories and sub-directories, try something recursive. E.g.:

#include <dirent.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void listOfDir(char * dirname, int level)
{
    struct dirent *direntp;
    DIR *dirp;
    char *subdirname;
    if ((dirp = opendir(dirname)) == NULL) 
    {
        return;
    }
    while ((direntp = readdir(dirp)) != NULL)
    {
        if(strcmp(direntp->d_name, ".")==0 || strcmp(direntp->d_name, "..")==0)
              continue; // skip current and parent directories
        printf("%*c%s\n", level, '>', direntp->d_name);
        if( direntp->d_type == 4)
        {
              // build child dir name and call listOfDir
              subdirname = (char*)malloc(strlen(direntp->d_name) + strlen(dirname) + 2);
              strcpy(subdirname, dirname);
              strcat(subdirname, "/");
              strcat(subdirname, direntp->d_name);
              listOfDir(subdirname, level+1);
              free(subdirname);
        }
    }
    closedir(dirp);
}

int main(int argc, char *argv[]) {
    struct dirent *direntp;
    DIR *dirp;
    if (argc != 2) {
        fprintf(stderr, "Usage: %s directory_name\n", argv[0]);
        return 1; 
    }
    listOfDir(argv[1], 1);
    return 0; 
}

Expression like printf("%*c", level, '>') just make indents for elach level of nesting

VolAnd
  • 6,367
  • 3
  • 25
  • 43