• linux下的文件扫描程序(转载)


    直接上代码了,这个比较容易理解。

    原代码有点问题,而且注释说的path也不一定为全目录,相对目录亦可。

    修改后在ubuntu 10.10上跑过,没问题。

    #include <sys/types.h>
    #include <dirent.h>
    #include <sys/stat.h>
    #include <unistd.h>
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    #include <string>
    #include <vector>
    #include <iostream>
    using namespace std;
    
    /***************************************************
    *作者   : 潘际勇
    *功能   : 扫描目录中所有文件, 并加入strvec中.
    *path   : 目录, 全路径. 如/home, /home/
    *strvec : 调用前,将strvec置空.strvec将被填充
    *返回值 : 返回 0, 成功执行; 返回 -1, 失败
    ***************************************************/
    int
    scan_allfile (const char *path, vector <string> &strvec)
    {
      DIR *dp;			//目录流
      struct dirent *entry;		//目录项信息
      struct stat statbuf;
    
    //打开目录, 判断目录是否存在
      if ((dp = opendir (path)) == 0)
        {
          fprintf (stderr, "open dir failed\n");
          return -1;
        }
    
    //读取目录信息
      while ((entry = readdir (dp)) != 0)
        {
          //忽略 . ..目录
          if (!strcmp (entry->d_name, ".") || !strcmp (entry->d_name, ".."))
    	{
    	  continue;
    	}
    
          //获取扫描到的文件的信息, 如果路径中没有'/', 则加'/', 加入strvec 
          //不管是目录,还是文件,都将被加进去.
          //tmp_path是一个全路径
          string tmp_path (path);
          if (*(tmp_path.end () - 1) != '/')
    	tmp_path += '/';
          tmp_path += entry->d_name;
          strvec.push_back (tmp_path);
    
          //如果是目录, 递归的扫描
          if (entry->d_type == 4)
    	{
    	  scan_allfile (tmp_path.c_str (), strvec);
    	}
          else
    	{
    	  //do nothing
    	}
        }
      closedir (dp);
      return 0;
    }
    
    int
    main ()
    {
      char *path = new char[255];
      cin >> path;
      vector < string > strvec;
    
      scan_allfile (path, strvec);
    
    //输出, 测试扫描是否正确
      for (vector < string >::iterator iter = strvec.begin ();
           iter != strvec.end (); ++iter)
        cout << *iter << endl;
    
      delete[]path;
      path = 0;
      return 0;
    }
    

    见图:

  • 相关阅读:
    关于研发核心团队建设的一些思考
    无法打开物理文件xxx.mdf操作系统错误 5:“5(拒绝访问。)” (Microsoft SQL Server,错误: 5120)的解决方法
    自适应网页设计(Responsive Web Design)
    css浮动与绝对定位小记
    WEB进度条控件
    GitHub上整理的一些工具
    雾里看花般的迷茫--货运APP
    揭秘史上最完美一步到位的搭建Andoriod开发环境
    我是如何在SQLServer中处理每天四亿三千万记录的
    货运APP产品魔力=卓越功能×情感诉求
  • 原文地址:https://www.cnblogs.com/yixiaoyang/p/1989735.html
Copyright © 2020-2023  润新知