1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
|
/**********************************************************
* Author : oyjb
* Email : jbouyang@126.com
* Last modified : 2015-09-13 23:01
* Filename : get_file_count.c
* Description : copy right for oyjb
* *******************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <errno.h>
#include <string.h>
#define MAX 1024
int
get_file_count(
const
char
*root);
int
main(
int
argc,
char
*argv[])
{
if
(argc < 2)
{
printf
(
"wrong usage.\n"
);
exit
(1);
}
int
total = 0;
total = get_file_count(argv[1]);
printf
(
"%s has %d files.\n"
, argv[1], total);
exit
(0);
}
/*
* The parameter for function of get_file_count is a filepath,represents a directory's root
* This function return the numbers of all regular files in this directory,include child directory
*/
int
get_file_count(
const
char
*root)
{
DIR *dir;
struct
dirent *ptr;
int
total = 0;
//numbers of files
char
path[MAX];
dir = opendir(root);
//open directory
if
(dir == NULL)
{
perror
(
"fail to open directory"
);
exit
(1);
}
errno
= 0;
while
( (ptr = readdir(dir)) != NULL)
{
//jump the . and ..
if
(
strcmp
(ptr->d_name,
"."
) == 0 ||
strcmp
(ptr->d_name,
".."
) == 0)
continue
;
/*
* 以下的得到子目录全路径的方法还可以是:
* sprintf(path, "%s/%s", root, ptr->d_name);
*/
sprintf
(path,
"%s/%s"
, root, ptr->d_name);
/*
path[0] = '\0';
strcat(path, root);
strcat(path, "/"); //you must be strcat the character "/",other than error.
strcat(path, ptr->d_name);
*/
/*
* 由于xfs文件系统在读取dirent的d_type时无法读取,因此需要转到stat函数处理,读取文件信息
* 否则下面的代码可换成:
* if (ptr->d_type == DT_DIR)
* total += get_file_count(path);
* if (ptr->d_type == DT_REG)
* ++total;
* 正是因为d_type与文件系统有关(应该是),所以最好还是用stat函数获取文件类型信息
*/
struct
stat sta;
if
(lstat(path, &sta) == -1)
{
printf
(
"%s\n"
, path);
perror
(
"fail to get file information."
);
return
0;
}
if
(S_ISDIR(sta.st_mode))
total += get_file_count(path);
else
if
(S_ISREG(sta.st_mode) || S_ISLNK(sta.st_mode))
++total;
}
if
(
errno
!= 0)
{
perror
(
"fail to read dir"
);
exit
(1);
}
closedir(dir);
return
total;
}
|
获取目录下的普通文件数目
最新推荐文章于 2022-08-31 10:35:25 发布