递归遍历一个目录下的所有文件和文件夹,统计各个类型文件所占的百分比
程序代码a.cpp(编译命令:g++ a.cpp -o a)
#include
#include
#include
#include
#include
#include
#include
struct FileStat
{
char m_Name[100]; //文件类型名
int m_Count; //文件个数统计(在main函数中计算)
float m_Percent; //在所有文件中占的百分比(在main函数中计算)
FileStat(const char* name)
{
strcpy(this -> m_Name, name);
this -> m_Count = 0;
this -> m_Percent = 0;
}
};
struct FileStat* fs[8] =
{
new FileStat("普通文件(REGULAR) "),
new FileStat("目录文件(DIRECTORY) "),
new FileStat("字符特殊文件(CHARACTER_SPECIAL)"),
new FileStat("块特殊文件(BLOCK_SPECIAL) "),
new FileStat("管道或FIFO(FIFO) "),
new FileStat("符号链接(SYMBOLIC_LINK) "),
new FileStat("套接字(SOCKET) "),
new FileStat("其他未知类型(UNKNOWN) ")
};
struct stat buf;
//遍历文件夹
void CheckDir(char* dir, int depth)
{
DIR *dp;
struct dirent *entry;
struct stat statbuf;
if ((dp = opendir(dir)) == NULL)
{
fprintf(stderr, "Cannot Open Directory: %s\n");
return;
}
chdir(dir);
while ((entry = readdir(dp)) != NULL)
{
lstat(entry -> d_name, &statbuf);
//遍历到文件夹
if (S_ISDIR(statbuf.st_mode))
{
if(strcmp(".", entry -> d_name) == 0 ||
strcmp("..", entry -> d_name) == 0)
{
continue;
}
//printf("%d|%*sDir:%s/\n", depth, depth, " ", entry -> d_name);
fs[1] -> m_Count++;
CheckDir(entry -> d_name, depth + 4);
}
else //遍历到文件
{
//printf("%d|%*sFile:%s | ", depth, depth, " ", entry -> d_name);
if (lstat(entry -> d_name, &buf) < 0)
{
printf("LSTAT ERROR");
continue;
}
if (S_ISREG(buf.st_mode))
{
//printf("普通文件 REGULAR\n");
fs[0] -> m_Count++;
}
else if (S_ISCHR(buf.st_mode))
{
//printf("字符特殊文件 CHARACTER SPECIAL\n");
fs[2] -> m_Count++;
}
else if (S_ISBLK(buf.st_mode))
{
//printf("块特殊文件 BLOCK SPECIAL\n");
fs[3] -> m_Count++;
}
else if (S_ISFIFO(buf.st_mode))
{
//printf("管道或FIFO FIFO\n");
fs[4] -> m_Count++;
}
else if (S_ISLNK(buf.st_mode))
{
//printf("符号连接 SYMBOLIC LINK\n");
fs[5] -> m_Count++;
}
else if (S_ISSOCK(buf.st_mode))
{
//printf("套接字 SOCKET\n");
fs[6] -> m_Count++;
}
else
{
//printf("未知类型 UNKNOWN MODE\n");
fs[7] -> m_Count++;
}
}
}
chdir("..");
closedir(dp);
}
int main(int argc, char *argv[])
{
if (argc != 2)
{
printf("Input Error: Argv[1] must be a file name!\n");
exit(1);
}
printf("Check Folder: %s\n", argv[1]);
CheckDir(argv[1], 0);
//计算m_Count和m_Percent
int i, total;
for(i = 0; i < 8; i++)
{
total += fs[i] -> m_Count;
}
for(i = 0; i < 8; i++)
{
fs[i] -> m_Percent = 1.0 * fs[i] -> m_Count / total;
}
//输出计算结果
printf(" STAT \n");
printf("============================================\n");
for(i = 0; i < 8; i++)
{
printf("%s | %7.3f%%\n", fs[i] -> m_Name, 100.0 * fs[i] -> m_Count / total);
}
printf("Done.\n");
return 0;
}
运行结果
END