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
readdir
and thedirent
structure is specified in POSIX, the contents of thedirent
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 dudereaddir
should be very helpful. – Some programmer dude