Sunday, July 30, 2006

Directories in c

This tutorial covers directory in c:

Before proceeding include the following file:

dirent.h:
Contains definition of DIR structure. Just similar to FILE structure you will see later.
To open a directory use
DIR* dir = opendir("..");
".." means open current directiory.
"." means parent directory.
else a sub directory or complete path e.g: “e:\\” remember why double slash??

Now the directory is opened how to loop for directories or files in this opened directory??
struct dirent* dent = dent=readdir(dir) ;
Reads next entry in the opened directory. entry may be a file or directory.

Finally to close opened directory:
closedir(dir);

The following code is self explanatory.

/*

file : dir.c

A tutorial in opening directories in c.

*/

#include

#include


int main(int argc,char **argv)

{

/*

A directory entry pointer.

*/

struct dirent* dent;

/*

open current directory.

".." means open current directiory.

*/

DIR* dir = opendir("..");

printf("\n***** DIR LISTING *****\n\n");

/*

if dir is null then open failed

may be due to directory is not present

or access is denied.

*/

if(dir)

{

/*

readdir reads next direcory entry.

returns struct dirent* which ->d_name contains name of directory entry.

entry may be a file or directory.

returns null after finishing all entries.

*/

while((dent=readdir(dir)))

{

FILE* fptr ;

printf(dent->d_name);

/*

try to open dir as a file in read mode.

if it's opened then it's actually a file.

else it's a directory.

*/

if(fptr = fopen(dent->d_name,"r"))

{

printf("\t\tFile") ;

fclose(fptr) ;

}

else

printf("\t\tDirectory") ;

printf("\n");

}

/*

close opened directory.

*/

closedir(dir);

}

else

printf("Err. opening directory\n");

printf("\n");

getchar();

return 0;

}

2 comments:

Faraz said...

This code can be optimized 2 folds over. In other words, half of what you've done.
But nonetheless, Good code.

Mohamed Mohab said...

But how to optimize this code?