第一种:结果出错
int browse_dir(string dir)
{
DIR *pDir;
struct dirent *pEnt;
struct stat statbuf;
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[0]=='.')&&(pEnt->d_name[1]=='.' || pEnt->d_name[1]==0))
{
continue;
}
//lstat(pEnt->d_name,&statbuf);
//将sprintf(fullpath, "%s/%s", dir.c_str(), pEnt->d_name); //获取全局路径
lstat(fullpath,&statbuf);
{
sFileName= dir + "/" + pEnt->d_name;
printf("directory->%s\n", sFileName.c_str());
// browse_dir(sFileName);
}
else
{
sFileName= dir +"/"+pEnt->d_name;
printf("file->%s\n",sFileName.c_str());
}
}
closedir(pDir);
return 0;
}
第2种写法:结果正确
void printdir(char *dir,int depth)
{
DIR *dp;
struct dirent *entry;
struct stat statbuf;
if((dp=opendir(dir))==NULL)
{
fprintf(stderr,"cannot open direntory:%s\n",dir);
return;
}
chdir(dir);
while((entry=readdir(dp))!=NULL)
{
lstat(entry->d_name,&statbuf);
if(S_ISDIR(statbuf.st_mode))
{
if(strcmp(".",entry->d_name)==0||strcmp("..",entry->d_name)==0)
continue;
printf("%*s%s/\n",depth,"",entry->d_name);
printdir(entry->d_name,depth+4);
}
else printf("%*s%s\n",depth,"",entry->d_name);
}
chdir("..");
closedir(dp);
}