main
関数を設計する
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;
/* ゼロ割り算を回避してプログラムの安定性を向上させる */
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
:ファイルの総数。