我编写了这个实际列出给定目录内容的函数。但是,我想让它告诉我有多少个文件和多少个目录。我尝试过这样的事情,但它并没有真正发挥作用:
if(dir->d_type == D_DIR)
directories++;
这是我的代码。我该如何修改它:
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
int main (void) {
DIR *d = opendir (".");
struct dirent *dir;
if (d != NULL) {
int files, directories = 0;
while(dir=readdir(d))
puts(dir->d_name);//Prints the actual names of the entries
//Closing the directory
(void) closedir (d);
} else
perror ("Couldn't open the directory");
return 0;
}
答案 0 :(得分:0)
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
int main (void) {
DIR *d = opendir (".");
struct dirent *dir;
if (d != NULL) {
int files, directories = 0;
while((dir=readdir(d)) != NULL) {
if (dir->d_type == DT_REG)
files++;
if(dir->d_type == DT_DIR)
directories++;
}
//Closing the directory
(void) closedir (d);
printf("%i Files and %i directories\n\n", files, directories);
} else
perror ("No such directory");
return 0;
}