设计 main
函数
主函数的主要功能是首先接收命令行参数并检查其有效性。然后调用 myftw
函数来计算各类文件的数量。最后计算文件类型的百分比并输出。
#include <dirent.h>
#include <limits.h>
#include <sys/stat.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#define FTW_F 1 /* 非目录文件的标志 */
#define FTW_D 2 /* 目录文件的标志 */
#define FTW_DNR 3 /* 不可读目录文件的标志 */
#define FTW_NS 4 /* 无法通过stat访问的文件的标志 */
static char *fullpath;
static size_t pathlen;
/* 定义处理文件的函数 */
typedef int Myfunc(const char *, const struct stat *, int);
static Myfunc myfunc;
static int myftw(char *, Myfunc *);
static int dopath(Myfunc *);
char *path_alloc(size_t *size);
static long nreg, ndir, nblk, nchr, nfifo, nslink, nsock, ntot;
int main(int argc, char *argv[])
{
int ret;
// 进行输入有效性检查
if (argc!= 2)
{
printf("无效的命令输入!\n");
exit(1);
}
/* 计算各类文件的数量 */
ret = myftw(argv[1], myfunc);
/* 计算文件总数 */
ntot = nreg + ndir + nblk + nchr + nfifo + nslink + nsock;
/* 避免除以0以提高程序稳定性 */
if (ntot == 0)
ntot = 1;
/* 打印各类文件的百分比 */
printf("普通文件 = %7ld, %5.2f %%\n", nreg,
nreg*100.0 / ntot);
printf("目录 = %7ld, %5.2f %%\n", ndir,
ndir*100.0 / ntot);
printf("块特殊文件 = %7ld, %5.2f %%\n", nblk,
nblk*100.0 / ntot);
printf("字符特殊文件 = %7ld, %5.2f %%\n", nchr,
nchr*100.0 / ntot);
printf("FIFO = %7ld, %5.2f %%\n", nfifo,
nfifo*100.0 / ntot);
printf("符号链接 = %7ld, %5.2f %%\n", nslink,
nslink*100.0 / ntot);
printf("套接字 = %7ld, %5.2f %%\n", nsock,
nsock*100.0 / ntot);
exit(ret);
}
*fullpath
:用于存储文件的完整路径。
pathlen
:用于存储文件路径的长度。
nreg
:普通文件的数量。
ndir
:目录文件的数量。
nblk
:块特殊文件的数量。
nchr
:字符特殊文件的数量。
nfifo
:命名管道的数量。
nslink
:符号链接文件的数量。
nsock
:套接字文件的数量。
ntot
:文件总数。