APUE统计目录各类文件个数(c++版)
来源:互联网 发布:不使用第三个变量 php 编辑:程序博客网 时间:2024/06/05 14:12
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; }}
运行:
阅读全文
1 0
- APUE统计目录各类文件个数(c++版)
- C语言,统计输入的字符各类的个数
- linux统计文件、文件目录个数
- Linux统计文件目录及其文件个数
- Linux统计文件、目录个数,文件行数
- Linux统计目录下的文件个数
- Linux 统计目录及其子目录文件个数
- 递归目录统计文件个数与行数
- linux 统计文件夹下目录、文件个数
- Linux 统计当前文件/目录个数
- 统计当前文件夹下的文件个数、目录个数
- 【APUE】文件和目录
- APUE文件和目录
- APUE文件和目录
- APUE-2文件/目录
- APUE------文件和目录
- [APUE]文件和目录
- Shell脚本统计指定目录下子目录中的文件个数
- 如何写一篇数据分析报告3
- 4-3 求序列和
- Netty入门
- SLF4J源码解析-LoggerFactory(二)
- Spring事务机制
- APUE统计目录各类文件个数(c++版)
- 深入浅出最大似然估计(Maximum Likelihood Estimation)
- Spring Boot中使用Spring-data-jpa
- java每日一练
- hibernate与mybatis的对比
- 线程基础:多任务处理——Fork/Join框架(要点2)
- C++数组形参的问题
- Python 08 面向对象的基本概念
- 1204:括号配对问题