【发布时间】:2020-06-17 18:43:36
【问题描述】:
我需要在一个目录中查找文件和文件夹的数量。在此之前我使用的是 MinGW 编译器,我尝试使用 d_type 但我无法编译我的代码。
而且我不在乎“。”和“..”目录。我不想计算它们。
所以我写了一个这样的程序。这个程序可以很容易地找到一个目录中有多少个文件和文件夹。
但是当我给一个新名称一个文件夹而不是新文件夹时,新文件夹(1)。该程序将该文件夹计算为一个文件。
我能做什么?我真的卡住了。我要找出多少个文件和多少个文件夹...
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
int
main(int argc, char *argv[])
{
int file_count = 0;
int dir_count = 0;
struct dirent * entry;
struct stat filestat;
size_t nfiles = 0, ndirs = 0;
DIR *dp;
if (argc != 2)
{
printf("usage: put 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 (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, "..")) {
continue;
}
stat(entry->d_name,&filestat);
if( S_ISDIR(filestat.st_mode) ){
ndirs++;
}
else
nfiles++;
}
closedir(dp);
printf("%lu Files, %lu Directories\n", nfiles, ndirs);
return(0);
}
【问题讨论】:
-
正如我之前所说,我不能使用 d_type 和 DT_REG。我无法在 Windows 上编译该代码。
-
好吧,你没有明确说出来。但我已删除链接并关闭投票。
标签: c io system-calls stat readdir