【Cocos2d-x】打印指定目录下所有文件
记得在#include处添加如下代码 :
无聊的时候写写代码,哇咔咔.以下是一个cocos2d-x打印指定目录下的所有文件.(跨平台的呦,C++初学者,代码污染请勿喷)...
- void HelloWorld::FindAllFile(string folderPath)
- {
- // Window处理方式
- #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
- _finddata_t FileInfo;
- string strfind = folderPath + "\\*";
- long Handle = _findfirst(strfind.c_str(), &FileInfo);
- if (Handle == -1L)
- {
- CCLog("can not match the folder path");
- return;
- }
- do{
- //判断是否有子目录
- if (FileInfo.attrib & _A_SUBDIR)
- {
- //这个语句很重要
- if( (strcmp(FileInfo.name,".") != 0 ) &&(strcmp(FileInfo.name,"..") != 0))
- {
- string newPath = folderPath + "\\" + FileInfo.name;
- FindAllFile(newPath);
- }
- }
- else
- {
- count++;
- CCLog("%s\\%s" , folderPath.c_str() , FileInfo.name);
- }
- }while (_findnext(Handle, &FileInfo) == 0);
- _findclose(Handle);
- #else
- CCLog(folderPath.c_str());
- DIR *dp;
- struct dirent* dirp;
- if((dp = opendir(folderPath.c_str())) == NULL)
- {
- CCLog("can not match the folder path");
- return;
- }
- while ((dirp=readdir(dp))!=NULL)
- {
- struct stat buf;
- stat(folderPath.c_str(), &buf);
- // 如果是目录
- if (S_ISDIR(buf.st_mode))
- {
- string path;
- if( (strcmp(dirp->d_name,".") != 0 ) &&(strcmp(dirp->d_name,"..") != 0))
- {
- path = folderPath + "/" + dirp->d_name;
- }
- //如果是目录,递归调用
- FindAllFile(path);
- }
- else
- {
- // 如果是文件直接打印
- CCLog("%s/%s\n",folderPath.c_str(),dirp->d_name);
- }
- }
- CCLog("\n");
- closedir(dp);
- #endif
- }
void HelloWorld::FindAllFile(string folderPath)
{
// Window处理方式
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
_finddata_t FileInfo;
string strfind = folderPath + "\\*";
long Handle = _findfirst(strfind.c_str(), &FileInfo);
if (Handle == -1L)
{
CCLog("can not match the folder path");
return;
}
do{
//判断是否有子目录
if (FileInfo.attrib & _A_SUBDIR)
{
//这个语句很重要
if( (strcmp(FileInfo.name,".") != 0 ) &&(strcmp(FileInfo.name,"..") != 0))
{
string newPath = folderPath + "\\" + FileInfo.name;
FindAllFile(newPath);
}
}
else
{
count++;
CCLog("%s\\%s" , folderPath.c_str() , FileInfo.name);
}
}while (_findnext(Handle, &FileInfo) == 0);
_findclose(Handle);
#else
CCLog(folderPath.c_str());
DIR *dp;
struct dirent* dirp;
if((dp = opendir(folderPath.c_str())) == NULL)
{
CCLog("can not match the folder path");
return;
}
while ((dirp=readdir(dp))!=NULL)
{
struct stat buf;
stat(folderPath.c_str(), &buf);
// 如果是目录
if (S_ISDIR(buf.st_mode))
{
string path;
if( (strcmp(dirp->d_name,".") != 0 ) &&(strcmp(dirp->d_name,"..") != 0))
{
path = folderPath + "/" + dirp->d_name;
}
//如果是目录,递归调用
FindAllFile(path);
}
else
{
// 如果是文件直接打印
CCLog("%s/%s\n",folderPath.c_str(),dirp->d_name);
}
}
CCLog("\n");
closedir(dp);
#endif
}
记得在#include处添加如下代码 :
- #if (CC_TARGET_PLATFORM != CC_PLATFORM_WIN32)
- #include <dirent.h>
- #include <sys/stat.h>
- #else
- #include <io.h>
- #endif
#if (CC_TARGET_PLATFORM != CC_PLATFORM_WIN32)
#include <dirent.h>
#include <sys/stat.h>
#else
#include <io.h>
#endif