linux下的文件扫描程序

来源:岁月联盟 编辑:exp 时间:2011-09-24

 不错,值得借鉴:
直接上代码了,这个比较容易理解。

原代码有点问题,而且注释说的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;
}

作者“風聲”