linux扫描目录下所有文件

linux扫描目录下所有文件

#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


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值