Reputation: 11
I have to find how many folders and how many regular files in a directory. I've tried to something but I couldn't even compile my code. I don't even know my program is right or not.When I tried to compile my code there are 2 type of error. One of them is error: struct dirent has no member named 'd_type' and 'DT_DIR' undeclared(first use in this function, DT_REG undeclared(first use in this function).
I'm using CodeBlocks with MinGW, if the error is about the my compiler; I have to use this IDE.
How can I fix my code?
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
int
main(int argc, char *argv[])
{
int file_count = 0;
int dir_count = 0;
struct dirent * entry;
DIR *dp;
if (argc != 2)
{
printf("usage: give directory_name\n");
exit(-1);
}
if ((dp = opendir(argv[1])) == NULL)
{
printf("Error: can't open %s\n", argv[1]);
exit(-2);
}
while ((entry= readdir(dp)) != NULL){
if (entry->d_type == DT_REG)
file_count++;
else if (entry->d_type == DT_DIR)
dir_count++;
}
closedir(dp);
printf(" %d Number of file ", file_count);
printf(" %d Number of folders", dir_count);
exit(0);
}
Upvotes: 1
Views: 528
Reputation: 129
Maybe you're missing some includes?
Here is my version
#include <dirent.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
int main(int argc, char *argv[]) {
DIR *dir;
struct dirent *ent;
size_t nfiles = 0, ndirs = 0;
if (argc != 2) {
fprintf(stderr, "Usage: %s directory\n", argv[0]);
return -1;
}
if (!(dir = opendir(argv[1]))) {
fprintf(stderr, "[!] Could not open directory `%s': %s\n", argv[1],
strerror(errno));
return -2;
}
while ((ent = readdir(dir))) {
// Ignore . and .. entries
if (!strcmp(ent->d_name, ".") || !strcmp(ent->d_name, "..")) {
continue;
}
if (ent->d_type == DT_REG) {
++nfiles;
} else if (ent->d_type == DT_DIR) {
++ndirs;
}
}
closedir(dir);
printf("%lu Files, %lu Directories\n", nfiles, ndirs);
return 0;
}
Upvotes: 1