C 如何仅计算路径中的目录数
我试图只计算路径中的目录,但它不起作用。所以,我不想同时给文件和目录编号,我只想要目录。你能帮帮我吗? 守则:C 如何仅计算路径中的目录数,c,file,counting,stat,C,File,Counting,Stat,我试图只计算路径中的目录,但它不起作用。所以,我不想同时给文件和目录编号,我只想要目录。你能帮帮我吗? 守则: int listdir(char *dir) { struct dirent *dp; struct stat s; DIR *fd; int count = 0; if ((fd = opendir(dir)) == NULL) { fprintf(stderr, "listdir: can't open %s\n", dir
int listdir(char *dir) {
struct dirent *dp;
struct stat s;
DIR *fd;
int count = 0;
if ((fd = opendir(dir)) == NULL) {
fprintf(stderr, "listdir: can't open %s\n", dir);
}
while ((dp = readdir(fd)) != NULL) {
if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
continue;
stat(dp->d_name, &s);
if (S_ISDIR(s.st_mode))
count++;
}
closedir(fd);
return count;
}
我想你想要
- 用C写的
- 计算路径中的目录数
- 计数函数将返回
值int
#include <stdio.h>
#include <glob.h>
#include <string.h>
#define MAX_PATH 1023
int countDirectories(char* dir)
{
char path[MAX_PATH] = "";
strcat(path, dir);
strcat(path, "/*");
glob_t globbuf;
long i, count = 0;
if (glob(path, GLOB_NOSORT | GLOB_ONLYDIR, NULL, &globbuf) == 0)
{
count = globbuf.gl_pathc;
for (i = 0; i < globbuf.gl_pathc; i++)
{
count += countDirectories(globbuf.gl_pathv[i]);
}
}
globfree(&globbuf);
return count;
}
int main(int argc, char* argv[])
{
int count;
if (argc > 1)
{
count = countDirectories(argv[1]);
}
else
{
count = countDirectories(".");
}
printf("there are %d directories.\n", count);
return 0;
}
然后您将收到如下输出:
path = /path/to/target/dir/*, there are N directories
谢谢。您的stat()调用将失败,因为您不在正确的目录中。您可以通过更改当前目录或生成完整路径并将stat作为参数来解决此问题
对于某些unix,您可以通过查看struct dirent(d_类型字段)优化stat调用
int listdir(char *dir) {
struct dirent *dp;
struct stat s;
DIR *fd;
int count = 0;
if ((fd = opendir(dir)) == NULL) {
fprintf(stderr, "listdir: can't open %s\n", dir);
}
chdir (dir); /* needed for stat to work */
while ((dp = readdir(fd)) != NULL) {
if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
continue;
#ifdef _DIRENT_HAVE_D_TYPE
switch (dp->d_type)
{
case DT_UNKNOWN:
stat(dp->d_name, &s);
if (S_ISDIR(s.st_mode)) count++;
break;
case DT_DIR:
count++;
break;
}
#else
stat(dp->d_name, &s);
if (S_ISDIR(s.st_mode)) count++;
#endif
}
closedir(fd);
return count;
}
使用
S_ISREG()
来判断目录条目是否是常规文件,否则它是一个目录(或链接)。它不起作用…你能解释一下怎么做吗?斯蒂安,我如何在windows上使用chdir?首先点击谷歌显示并编辑:)你可以使用我的countDirectories
作为你的listdir
函数glob
是按模式搜索文件/目录的功能。使用flagGLOB_ONLYDIR
,我们只能搜索目录。因此,您可以在路径中找到目录数。
int listdir(char *dir) {
struct dirent *dp;
struct stat s;
DIR *fd;
int count = 0;
if ((fd = opendir(dir)) == NULL) {
fprintf(stderr, "listdir: can't open %s\n", dir);
}
chdir (dir); /* needed for stat to work */
while ((dp = readdir(fd)) != NULL) {
if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
continue;
#ifdef _DIRENT_HAVE_D_TYPE
switch (dp->d_type)
{
case DT_UNKNOWN:
stat(dp->d_name, &s);
if (S_ISDIR(s.st_mode)) count++;
break;
case DT_DIR:
count++;
break;
}
#else
stat(dp->d_name, &s);
if (S_ISDIR(s.st_mode)) count++;
#endif
}
closedir(fd);
return count;
}