计算目录中文件和文件夹的数量 [英] Counting number of files and folders in directory

查看:183
本文介绍了计算目录中文件和文件夹的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用C计算目录中文件和文件夹的数量。我没有头绪。我无法编写单行代码。
我不在乎当前目录。和父目录。.
运行程序时,我必须提供路径名,例如 C:/ Users / me / Documents / Example。

How can I count the number of files and folders in a directory using C. I have no clue. I couldn't write single line code. I do not care about current directory . and the parent directory.. I have to give a pathname for example "C:/Users/me/Documents/Example" while I'm running the program.

我需要一个类似此目录中有2个文件夹和4个文件的输出。

And I need a output like " There are 2 folders and 4 files in this directory".

推荐答案

对于Linux操作系统



下面的代码应列出 dir_path 中的所有文件和子目录(对于当前目录,请使用 dir_path =。 )。

for linux os

The code below shall list all files and sub-directories in dir_path (for current directory use dir_path = ".").

描述

此说明来自man7.org 链接

This description qouted from man7.org link

struct dirent *readdir(DIR *dirp);



readdir()



The readdir()函数返回指向 dirent结构
的指针,该指针表示目录流中指向下一个目录项
dirp 。在到达目录的末端
流或发生错误时,它返回 NULL 。有关更多详细信息,请转到上面的 man7.org 链接。

readdir()

The readdir() function returns a pointer to a dirent structure representing the next directory entry in the directory stream pointed to by dirp. It returns NULL on reaching the end of the directory stream or if an error occurred. for further details go to the link above for man7.org.

#include <stdio.h> 
#include <dirent.h> 

int main(void) 
{ 
   /* de is Pointer for directory entry */
    struct dirent *de;  
    const char* dir_path = "C:/Users/me/Documents/Example";
    /*opendir() returns a pointer of DIR type.*/  
    DIR *dr = opendir(dir_path); 

    if (dr == NULL)  /* opendir returns NULL if couldn't open directory */
    { 
        printf("Could not open current directory" ); 
        return 0; 
    } 

    while ((de = readdir(dr)) != NULL){
        printf("%s\n", de->d_name); 
    }
    closedir(dr);     
    return 0; 
}



对于Windows操作系统



对于Windows,请使用头文件: fileapi.h 在此处查看Microsoft文档: fileapi.h

for windows os

for windows use the header file: fileapi.h see microsoft docs here: fileapi.h

此问题之前在下面的链接中使用 FindFirstFile FindNextFile FindClose 函数。

this question answered before in SO in the link below using the FindFirstFile, FindNextFile and FindClose functions.

请查看链接中的答案:用C编程语言在Windows中列出目录

please review the answer in the link: list directory in windows in C programming language

这篇关于计算目录中文件和文件夹的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆