1
votes

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

1
While readdir and the dirent structure is specified in POSIX, the contents of the dirent structure (defined in the <dirent.h> header file) is usually extended by implementations and actual operating systems. Some operating systems includes information like file type (regular file, pipe, directory etc.). But you don't tell us your OS so we can't point you further, other than telling you to read the manual page (man readdir).Some programmer dude
@ Some programmer dude sorry,you're right, I'm using cloud9 for this and if I got it right the operating system is Ubuntu 14.04judy
Then this Linux manual page for readdir should be very helpful.Some programmer dude

1 Answers

0
votes

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