2014年9月5日 星期五

【Cocos2d-x】打印指定目录下所有文件

http://koyoter.blog.51cto.com/6156214/1203134

原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 、作者信息和本声明。否则将追究法律责任。http://koyoter.blog.51cto.com/6156214/1203134
无聊的时候写写代码,哇咔咔.以下是一个cocos2d-x打印指定目录下的所有文件.(跨平台的呦,C++初学者,代码污染请勿喷)...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
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处添加如下代码:
1
2
3
4
5
6
#if (CC_TARGET_PLATFORM != CC_PLATFORM_WIN32)
    #include <dirent.h>
    #include <sys/stat.h>
#else
    #include <io.h>
#endif

更多Cocos2d-x开发博文尽在 Koyoter's Blog
原文标题:【Cocos2d-x】打印指定目录下所有文件