日期:2014-05-16  浏览次数:20748 次

谁能给我一段linux下遍历文件夹读取所有文件名的程序?或者帮我看看我的
下面这个是我写的,不好用啊,lstat还出错。
#include   <string>
#include   <vector>
#include   <iostream>
using   namespace   std;
#include   <errno.h>
#include   <sys/types.h>
#include   <sys/stat.h>
#include   <dirent.h>
#ifndef   PATH_MAX
#define   PATH_MAX   1024
#endif


vector <string>   filenames;

static   int   myftw(const   char   *   pathname);
static   int   browseDir(const   char   *   pathname);

int   main(int   argc,   char   *   argv[])
{
if(   myftw( "/home/chendong/b ")   ==   0   )
{
vector <string> ::iterator   it;
for(it   =   filenames.begin();   it   !=   filenames.end();   it++)
cout < <*it < <endl;
return   0;
}
else
return   -1;
}

static   int   myftw(const   char   *   pathname)
{
return   (browseDir(pathname)   );
}

static   int   browseDir(const   char   *   pathname)
{
char   *   fullpath   =   (char   *)   malloc(PATH_MAX);
strcpy(fullpath,   pathname);

char   *   ptr   =   fullpath;
ptr   +=   strlen(fullpath);
*ptr++   =   '/ ';
*ptr   =   0;

struct   stat   statbuf;
if(lstat(fullpath,   &statbuf)   <   0)
{
perror( "lstat: ");
}

if(   S_ISREG(statbuf.st_mode)   )
{
filenames.push_back(fullpath);
return   0;
}

if(   S_ISDIR(statbuf.st_mode)   )
{
DIR   *   dp;
struct   dirent   *   dirp;

if(   (dp   =   opendir(fullpath))   ==   NULL)
return   -1;

while(   (dirp   =   readdir(dp))   !=   NULL)
{
if(strcmp(dirp-> d_name,   ". ")   ==   0   ||   strcmp(dirp-> d_name,   ".. ")   ==   0)
continue;

strcpy(ptr,   dirp-> d_name);
if(   browseDir(fullpath)   ==   -1   )
break;
}

if(closedir(dp)   <   0)
return   -1;
}
return   0;
}


------解决方案--------------------
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>
#include <errno.h>
#include <vector>
#include <string>

using namespace std;

vector <string> filenames;

int browse_dir(string dir)
{
DIR *pDir;
struct dirent *pEnt;
string sFileName;

pDir = opendir(dir.c_str());
if (pDir == NULL) {
if (errno == ENOTDIR) {
filenames.push_back(dir);
return 0;
}
perror(dir.c_str());
return -1;
}


while ((pEnt=readdir(pDir))!= NULL) {
if ((pEnt-> d_name