cocos2d-x 实现跨平台的目录遍历
2013-11-27 13:48
323 查看
#ifdef _WIN32 #include <io.h> #else #include <unistd.h> #include <stdio.h> #include <dirent.h> #include <sys/stat.h> #endif
win32平台引用io.h里面的信息。
主要定义了一个void dfsFolder(string folderPath, int depth = 0);方法对其进行递归遍历。
具体的实现为
1 void dfsFolder( string folderPath, int depth) 2 { 3 #ifdef WIN32 4 _finddata_t FileInfo; 5 string strfind = folderPath + "\\*"; 6 long Handle = _findfirst(strfind.c_str(), &FileInfo); 7 8 if (Handle == -1L) 9 { 10 cerr << "can not match the folder path" << endl; 11 exit(-1); 12 } 13 do{ 14 //判断是否有子目录 15 if (FileInfo.attrib & _A_SUBDIR) 16 { 17 //这个语句很重要 18 if( (strcmp(FileInfo.name,".") != 0 ) &&(strcmp(FileInfo.name,"..") != 0)) 19 { 20 string newPath = folderPath + "\\" + FileInfo.name; 21 dfsFolder(newPath); 22 } 23 } 24 else 25 { 26 string filename = (folderPath + "\\" + FileInfo.name); 27 28 cout << folderPath << "\\" << FileInfo.name << " " << endl; 29 } 30 }while (_findnext(Handle, &FileInfo) == 0); 31 32 _findclose(Handle); 33 #else 34 DIR *dp; 35 struct dirent *entry; 36 struct stat statbuf; 37 if((dp = opendir(folderPath.c_str())) == NULL) { 38 fprintf(stderr,"cannot open directory: %s\n", folderPath.c_str()); 39 return; 40 } 41 chdir(folderPath.c_str()); 42 while((entry = readdir(dp)) != NULL) { 43 lstat(entry->d_name,&statbuf); 44 if(S_ISDIR(statbuf.st_mode)) { 45 46 if(strcmp(".",entry->d_name) == 0 || 47 strcmp("..",entry->d_name) == 0) 48 continue; 49 printf("%*s%s/\n",depth,"",entry->d_name); 50 dfsFolder(entry->d_name,depth+4); 51 } else { 52 string filename = entry->d_name; 53 54 printf("%*s%s\n",depth,"",entry->d_name); 55 } 56 } 57 chdir(".."); 58 closedir(dp); 59 #endif 61 }
chdir 是C语言中的一个系统调用函数(同cd),其中对目录"."及".."进行特殊的判断,因为"."是表示当前目录,".."表示父目录。
如果不进行特殊判定的话则进入死循环。
转自:http://www.cnblogs.com/tickdream/p/3315726.html
相关文章推荐
- cocos2d-x 实现跨平台的目录遍历
- cocos2d-x 实现跨平台的目录遍历
- cocos2d-x 实现跨平台的目录遍历
- 跨平台的目录遍历实现方法(windows和linux已经测试)
- c++ 实现跨平台的目录遍历
- cocos2d-x 实现目录的遍历 和 文件的全拷贝
- C++ 实现跨平台的目录遍历
- shell实现遍历某一目录并将该文件夹下的文件名字变为大/小写
- Qt实现遍历文件夹和文件目录(递归)
- [C/C++标准库]_[初级]_[获取文件的所在目录跨平台实现]
- php5中用迭代器实现目录遍历
- python实现目录递归遍历
- Linux下 C语言实现遍历指定目录下指定格式的文件
- 递归遍历Linux下的目录文件源码实现
- cocos2d-x3.2源码分析(一)类FileUtils--实现把资源放在Resources文件目录下达到多平台的引用
- PHP实现遍历、复制、删除目录
- [C/C++标准库]_[初级]_[获取文件的所在目录跨平台实现]
- CFileFind类实现的目录树遍历
- (跨平台)cocos2d-x C++ or Object-C(前端)调用C# webservices(后台),实现交叉编译到Android/IOS/WinPhone等移动终端设备
- linux下实现指定目录的简单遍历输出