zoukankan      html  css  js  c++  java
  • linux下遍历目录

    项目中需要遍历目录并对目录下的所有文件进行处理分析,于是先实现一下遍历目录的功能

    实现代码:

     1 #include <unistd.h>
     2 #include <dirent.h>
     3 #include <iostream>
     4 #include <stdio.h>
     5 #include <stdlib.h>
     6 #include <string.h>
     7 #include <sys/stat.h>
     8 
     9 using namespace std;
    10 
    11 void traverseDir(char *pPath, int nDeepth);
    12 
    13 int main(int argc, char **argv)
    14 {
    15     for (int i = 1; i < argc; ++i)
    16     {
    17         traverseDir(argv[i], 0);
    18     }
    19 
    20     return 0;
    21 }
    22 
    23 void traverseDir(char *pPath, int nDeepth)
    24 {
    25     DIR *pDir = NULL;
    26     struct dirent *pSTDirEntry;
    27     char *pChild = NULL;
    28 
    29 
    30     if ((pDir = opendir(pPath)) == NULL)
    31     {
    32         return ;
    33     }
    34     else
    35     {
    36         while ((pSTDirEntry = readdir(pDir)) != NULL)
    37         {
    38             if ((strcmp(pSTDirEntry->d_name, ".") == 0) || (strcmp(pSTDirEntry->d_name, "..") == 0))
    39             {
    40                 continue;
    41             }
    42             else
    43             {
    44                 for (int i = 0; i < nDeepth; i++)
    45                 {
    46                     cout << "	";
    47                 }
    48                 cout << pSTDirEntry->d_name << endl;
    49 
    50                 if (pSTDirEntry->d_type & DT_DIR)
    51                 {
    52                     pChild = (char*)malloc(sizeof(char) * (NAME_MAX + 1));
    53                     if (pChild == NULL)
    54                     {
    55                         perror("memory not enough.");
    56                         return ;
    57                     }
    58                     memset(pChild, 0, NAME_MAX + 1);
    59                     strcpy(pChild, pPath);
    60                     strcat(pChild, pSTDirEntry->d_name);
    61                     traverseDir(pChild, nDeepth + 1);
    62                     free(pChild);
    63                     pChild = NULL;
    64                 }
    65             }
    66         }
    67         closedir(pDir);
    68     }
    69 }

    此代码仅仅实现了遍历的功能,输出界面美观性没有考虑,而且也不太健壮,比如执行以下命令:

    1 ./Dir ../
    2 ./Dir ..

    第二行的就无法递归遍历文件夹,因为没有对路径结尾的/做处理。

    使用到的函数是opendir、readdir、closedir,还有结构体dirent以及DIR

    没有什么太难的地方,只是有一点需要注意,判断一个路径是不是目录应该使用pSTDirEntry->d_type & DT_DIR 判断相与的值是否等于零,不等于0则为目录

    参考:http://blog.csdn.net/pengqianhe/article/details/8567955

  • 相关阅读:
    关于 IIS 上运行 ASP.NET Core 站点的“HTTP 错误 500.19”错误
    下单快发货慢:一个 JOIN SQL 引起 SqlClient 读取数据慢的奇特问题
    ASP.NET Core 2.2 项目升级至 3.0 备忘录
    corefx 源码学习:SqlClient 是如何同步建立 Socket 连接的
    Chimee
    electron-vue:Vue.js 开发 Electron 桌面应用
    H5网页适配 iPhoneX,就是这么简单
    经典文摘:饿了么的 PWA 升级实践(结合Vue.js)
    Table Dragger
    分享8个网站开发中最好用的打印页面插件
  • 原文地址:https://www.cnblogs.com/lit10050528/p/4056044.html
Copyright © 2011-2022 走看看