user4093559
user4093559

Reputation:

reading every file in directories (unix/posix)

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; 
}

Upvotes: 0

Views: 358

Answers (1)

VolAnd
VolAnd

Reputation: 6407

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

Upvotes: 1

Related Questions