4.20.cpp
#include <iostream>
#include <sys/stat.h>
#include <string.h>
#include <stdexcept>
#include <memory>
#include <dirent.h>
using namespace std;
class Dir
{
public:
string dirname;
int nreg;
int nblk;
int nchr;
int ndir;
int nslink;
int nfifo;
int nsock;
int ntotal;
private:
struct stat* statbuf;
DIR *dp;
struct dirent *dirp;
private:
void isFile()
{
switch (statbuf->st_mode & S_IFMT)
{
case S_IFREG:
++nreg; break;
case S_IFBLK:
++nblk; break;
case S_IFCHR:
++nchr; break;
case S_IFLNK:
++nslink; break;
case S_IFIFO:
++nfifo; break;
case S_IFSOCK:
++nsock; break;
default:
throw out_of_range("未知类型文件");
}
}
void isDir()
{
++ndir;
if ((dp = opendir(dirname.c_str())) == NULL)
throw out_of_range("打开目录失败");
while ((dirp = readdir(dp)) != NULL)
{
if (strcmp(dirp->d_name,".") == 0 || strcmp(dirp->d_name,"..") ==0)
continue;
string ndirname = dirname + "/" + dirp->d_name;
cout << ndirname << endl;
unique_ptr<Dir> dir(new Dir(ndirname));
nreg += dir->nreg;
nchr += dir->nchr;
nblk += dir->nblk;
nslink += dir->nslink;
ndir += dir->ndir;
nfifo += dir->nfifo;
nsock += dir->nsock;
ntotal += dir->ntotal;
}
}
public:
Dir(const string& s):dirname(s),nreg(0),nblk(0),ndir(0),nfifo(0),nchr(0)
,nsock(0),nslink(0),ntotal(0),statbuf(new struct stat)
{
if (lstat(dirname.c_str(),statbuf) < 0)
throw out_of_range("lstat error\n");
if (S_ISDIR(statbuf->st_mode) == 0)
isFile();
else if (S_ISLNK(statbuf->st_mode) != 0)
++nslink;
else
isDir();
ntotal = nreg + nblk + ndir + nfifo + nchr + nsock + nslink;
}
void display()
{
cout << "********************************************" << endl;
cout << "普通文件总量: " << nreg << endl;
cout << "字符特殊文件总量: " << nchr << endl;
cout << "块特殊文件总量: " << nblk << endl;
cout << "符号链接总量: " << nslink << endl;
cout << "套接字文件总量: " << nsock << endl;
cout << "目录文件总量: " << ndir << endl;
cout << "管道文件总量: " << nfifo << endl;
cout << "文件总量: " << ntotal << endl;
cout << "********************************************" << endl;
}
~Dir()
{
if (S_ISDIR(statbuf->st_mode) != 0)
closedir(dp);
if (statbuf != NULL)
delete statbuf;
}
};
int main(int argc,char* argv[])
{
try
{
if (argc != 2)
throw domain_error("add <filename>");
Dir dir(argv[1]);
dir.display();
}
catch(const exception& e)
{
cout << e.what() << endl;
}
}
运行: