tags:

views:

647

answers:

6

How can I count the number of files in a directory using C on linux platform.

+4  A: 

See readdir.

KevinDTimm
+11  A: 

No guarantee that this code compiles, and it's really only compatible with Linux and the BSDs:

#include <dirent.h>

...

int file_count = 0;
DIR * dirp;
struct dirent * entry;

dirp = opendir("path"); /* There should be error handling after this */
while ((entry = readdir(dirp)) != NULL) {
    if (entry->d_type == DT_REG) { /* If the entry is a regular file */
         file_count++;
    }
}
closedir(dirp);
Michiel Buddingh'
If you want to process files in subdirectories, you can recurse when you encounter a directory entry. Make sure to exclude "." and ".." if you do this.
Jay Conrod
Good job on catching the dirent include.
Michiel Buddingh'
Aren't `opendir`, `readdir` and `closedir` POSIX.1-2001?
dreamlax
Yes, they are POSIX functions.
penguru
POSIX specifies only d_ino and d_name as members of the dirent-structure. This code tests for d_type, which is platform-specific.
Michiel Buddingh'
A: 

Thanks a lot! :-) This really helps me!

A: 

Its good... Have fun.

SreeKumar

sreekumar
A: 

How can I count the number of files in a directory using C on Windows Platform?

Sunayana
A: 

Very Helpfull..

Rajendra