linux下的檔案掃描程式

來源:互聯網
上載者:User

 不錯,值得借鑒:
直接上代碼了,這個比較容易理解。

原代碼有點問題,而且注釋說的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;
}

作者“風聲”

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.