Search code examples
cdirectorysystem-callsopendir

Open() system call for directories and accessing files in sub-directories


I'm trying to open a directory and access all it's files and sub-directories and also the sub-directories files and so on(recursion). I know i can access the files and the sub-directories by using the opendir call, but i was wondering if there is a way to do so by using the open() system call(and how?), or does the open system call only refers to files?

#include <stdio.h> 
#include <dirent.h> 

int main(void) 
{ 
 struct dirent *de;  // Pointer for directory entry 

// opendir() returns a pointer of DIR type.  
DIR *dr = opendir("."); 

if (dr == NULL)  // opendir returns NULL if couldn't open directory 
{ 
    printf("Could not open current directory" ); 
    return 0; 
} 


while ((de = readdir(dr)) != NULL) 
        printf("%s\n", de->d_name); 

closedir(dr);     
return 0; 
 } 

the following code gives me the names of the files in my directory and the names of the sub-folders, but how can I differ a file from a sub-folder so i can use recursion to access the files in the sub-folder?

any help would be appreciated


Solution

  • you will need to have the struct stat and the macro S_ISDIR from the , if you want to check if it is a file you can use the same method but with the macro S_ISREG. Also when you use structures is better to allocate memory before using them.

    #include <stdio.h> 
    #include <dirent.h> 
    #include <sys/stat.h>
    
    int main(void) 
    { 
     struct dirent *de = malloc(sizeof(struct dirent));  // Pointer for directory entry 
     struct stat *info; = malloc(sizeof(struct stat));
    
    // opendir() returns a pointer of DIR type.  
    DIR *dr = opendir("."); 
    
    if (dr == NULL)  // opendir returns NULL if couldn't open directory 
    { 
        printf("Could not open current directory" ); 
        return 0; 
    } 
    
    
    while ((de = readdir(dr)) != NULL) 
     {
       if((S_ISDIR(info->st_mode)
        printf("Directory:%s \n", de->d_name); 
       else printf("File:"%s \n,de->d_name);
     }
    closedir(dr);     
    return 0; 
    }