文章为网络上复制,仅供收藏学习使用.
C++ 实现跨平台的目录遍历
引用头文件:
#ifdef _WIN32
#include <io.h>
#else
#include <unistd.h>
#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
#endif
实现代码:
<span style="font-size:14px;">void dfsFolder( string folderPath, int depth)
{
#ifdef WIN32
_finddata_t FileInfo;
string strfind = folderPath + "\\*";
long Handle = _findfirst(strfind.c_str(), &FileInfo);
if (Handle == -1L)
{
cerr << "can not match the folder path" << endl;
exit(-1);
}
do{
//判断是否有子目录
if (FileInfo.attrib & _A_SUBDIR)
{
//这个语句很重要
if( (strcmp(FileInfo.name,".") != 0 ) &&(strcmp(FileInfo.name,"..") != 0))
{
string newPath = folderPath + "\\" + FileInfo.name;
dfsFolder(newPath);
}
}
else
{
string filename = (folderPath + "\\" + FileInfo.name);
cout << folderPath << "\\" << FileInfo.name << " " << endl;
}
}while (_findnext(Handle, &FileInfo) == 0);
_findclose(Handle);
#else
DIR *dp;
struct dirent *entry;
struct stat statbuf;
if((dp = opendir(folderPath.c_str())) == NULL) {
fprintf(stderr,"cannot open directory: %s\n", folderPath.c_str());
return;
}
chdir(folderPath.c_str());
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);
dfsFolder(entry->d_name,depth+4);
} else {
string filename = entry->d_name;
printf("%*s%s\n",depth,"",entry->d_name);
}
}
chdir("..");
closedir(dp);
#endif
}</span>
chdir 是C语言中的一个系统调用函数(同cd),其中对目录"."及".."进行特殊的判断,因为"."是表示当前目录,".."表示父目录。
如果不进行特殊判定的话则进入死循环。