不錯,值得借鑒:
直接上代碼了,這個比較容易理解。
原代碼有點問題,而且注釋說的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;
}
作者“風聲”