#include<sys/types.h>
#include<dirent.h>
#include<sys/stat.h>
#include<unistd.h>
#include<stdio.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;
}
最后约定一下自己的代码习惯
代码中文件,目录等取名
dir 目录, 目录路径 如/home/pan
file 文件名 如 hello.c abc.txt pan(pan 是一个目录名称)不含路径.
path 含全路径的文件名. 如/home/pan(pan虽然为一文件夹, 但也是/home的文件) /home/b.txt
/home/pan/a.txt