Linux下如何对目录中的文件进行统计

Linux下如何对目录中的文件进行统计,第1张

在本文中,将展示几种查找 Linux 目录中的文件数量的不同方法。

统计目录中的文件数量

统计目录中文件的最简单方法是使用ls每行列出一个文件,并将输出通过管道符传递给wc计算数量:

[root@localhost ~]# ls -1U /etc |wc -l

执行上面的 命令 将显示所有文件的总和,包括目录和符号链接。-1选项表示每行列出一个文件,-U告诉ls不对输出进行排序,这使 命令 的执行速度更快。ls -1U命令不计算隐藏文件。如果只想计算文件而不包括目录,请使用以下命令:

[root@localhost ~]# ls -1Up /etc |grep -v /|wc -l

-p选项强制ls将斜杠(/)指示符附加到目录。输出结果通过管道符传递到grep -v命令,排除包含斜杠的行,并计算数量。

为了更好地控制列出的文件,使用find命令而不是ls:

[root@localhost ~]# find /etc -maxdepth 1 -type f |wc -l

-type f选项告诉find仅列出文件(包括隐藏文件),-maxdepth 1将搜索限制到第一级目录。

递归统计目录中的文件

如果想要统计目录中的文件数量,并包括子目录中的,可以使用find命令:

[root@localhost ~]# find /etc -type f|wc -l

用来统计文件的另一个命令是tree,它以树状格式列出目录的内容:

[root@localhost ~]# yum -y install tree

[root@localhost ~]# tree /root

输出的内容底部会显示有多少目录,和多少文件。

总结

在本文中,将展示几种查找Linux目录中的文件数量的不同方法。

#include <stdio.h>

#include <stdlib.h>

#include <dirent.h>

#include <errno.h>

#include <string.h>

#define MAX 1024

int get_file_count(char *root)

{

DIR *dir

struct dirent * ptr

int total = 0

char path[MAX]

dir = opendir(root)/* 打开目录*/

if(dir == NULL)

{

perror("fail to open dir")

exit(1)

}

errno = 0

while((ptr = readdir(dir)) != NULL)

{

//顺序读取每一个目录项;

//跳过“..”和“.”两个目录

if(strcmp(ptr->d_name,".") == 0 || strcmp(ptr->d_name,"..") == 0)

{

continue

}

//printf("%s%s/n",root,ptr->d_name)

//如果是目录,则递归调用 get_file_count函数

if(ptr->d_type == DT_DIR)

{

sprintf(path,"%s%s/",root,ptr->d_name)

//printf("%s/n",path)

total += get_file_count(path)

}

if(ptr->d_type == DT_REG)

{

total++

printf("%s%s/n",root,ptr->d_name)

}

}

if(errno != 0)

{

printf("fail to read dir") //失败则输出提示信息

exit(1)

}

closedir(dir)

return total

}

int main(int argc, char * argv[])

{

int total

if(argc != 2)

{

printf("wrong usage/n")

exit(1)

}

total = get_file_count(argv[1])

printf("%s ha %d files/n",argv[1],total)

return 0

}


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/yw/8967279.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-23
下一篇 2023-04-23

发表评论

登录后才能评论

评论列表(0条)

保存