如何在Linux平台上使用C计算目录中的文件数量。使用C计算目录中文件的数量C
12
A
回答
32
不能保证此代码编译,它真的只与Linux和BSD系统兼容:
#include <dirent.h>
...
int file_count = 0;
DIR * dirp;
struct dirent * entry;
dirp = opendir("path"); /* There should be error handling after this */
while ((entry = readdir(dirp)) != NULL) {
if (entry->d_type == DT_REG) { /* If the entry is a regular file */
file_count++;
}
}
closedir(dirp);
6
参见readdir
。
-2
如果你不关心当前目录.
和这样的人的父目录..
:
drwxr-xr-x 3 michi michi 4096 Dec 21 15:54 .
drwx------ 30 michi michi 12288 Jan 3 10:23 ..
你可以做这样的事情:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
int main (void){
size_t count = 0;
struct dirent *res;
struct stat sb;
const char *path = "/home/michi/";
if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)){
DIR *folder = opendir (path);
if (access (path, F_OK) != -1){
if (folder){
while ((res = readdir (folder))){
if (strcmp(res->d_name, ".") && strcmp(res->d_name, "..")){
printf("%zu) - %s\n", count + 1, res->d_name);
count++;
}
}
closedir (folder);
}else{
perror ("Could not open the directory");
exit(EXIT_FAILURE);
}
}
}else{
printf("The %s it cannot be opened or is not a directory\n", path);
exit(EXIT_FAILURE);
}
printf("\n\tFound %zu Files\n", count);
}
输出:
1) - .gnome2
2) - .linuxmint
3) - .xsession-errors
4) - .nano
5) - .kde
6) - .xsession-errors.old
7) - .gnome2_private
8) - Public
9) - .gconf
10) - .bashrc
11) - .macromedia
12) - .thunderbird
13) - Pictures
14) - .profile
15) - .cinnamon
16) - .pki
17) - Compile
18) - Desktop
19) - .Private
20) - .cache
21) - .Xauthority
22) - .ICEauthority
23) - VirtualBox VMs
24) - .bash_history
25) - .mozilla
26) - .local
27) - .config
28) - .codeblocks
29) - Documents
30) - .bash_logout
31) - Videos
32) - Templates
33) - Downloads
34) - .adobe
35) - .gphoto
36) - Music
37) - .dbus
38) - .ecryptfs
39) - .sudo_as_admin_successful
40) - .gnome
Found 40 Files
相关问题
- 1. 使用JavaScript/nodejs计算目录中的文件数量?
- 2. 计算一个文件夹中的目录数C++ windows
- 3. C++文件/目录统计与变量
- 4. 计算C文本文件中完整基因的数量C
- 5. 使用VBS计算.c文件中#defines的数量
- 6. 计算c中某个特定目录下文件夹内的文件数
- 7. 使用c#计算Zip文件中的文件数
- 8. 使用Python浏览目录和计算目录中的文件
- 9. 使用dirent不能再次运行,计算C中目录中文件的数量。
- 10. 计算文件中的行数 - C
- 11. 计算文件中的字符数C#
- 12. 使用C#计算PDF文档中的减号数目
- 13. C++ - 加载所有文件名+计算当前目录中文件的数量+筛选文件扩展名
- 14. 计数的文件与目录和子目录C++
- 15. 计算目录中文件的数量python
- 16. Android - 计算服务器目录中文件的数量
- 17. 你如何计算文件中的整数数量? (C++)
- 18. 如何使用Python计算目录中的文件数
- 19. 使用c计算文件中的新行c
- 20. treeview的计算机目录c#
- 21. 如何计算使用C++的文件中的行数?
- 22. 使用C++从目录和子目录返回矢量中的文件
- 23. 计算在C++头文件中定义的方法数量
- 24. C++ - 计算文件中元音的数量
- 25. 如何使用C来计算文件中的字节数?
- 26. C++使用类来计算文件中的行数
- 27. 计算邮件数目标C
- 28. 如何计算使用bash的路径中的目录数量?
- 29. C/C++大量计算
- 30. 计算目录中的文件
如果要处理子目录中的文件,可以在遇到目录条目时递归。确保排除“。”和“..”,如果你这样做。 – 2009-07-13 19:07:27
抓住dirent包括好工作。 – 2009-07-13 19:09:44