Ejemplo n.º 1
0
bool FileUtils::createDirectory(const std::string& path)
{
    LOG_ASSERT(!path.empty(), "Invalid path");

    if (isDirectoryExist(path))
        return true;

    // Split the path
    size_t start = 0;
    size_t found = path.find_first_of("/\\", start);
    std::string subpath;
    std::vector<std::string> dirs;

    if (found != std::string::npos)
    {
        while (true)
        {
            subpath = path.substr(start, found - start + 1);
            if (!subpath.empty())
                dirs.push_back(subpath);
            start = found + 1;
            found = path.find_first_of("/\\", start);
            if (found == std::string::npos)
            {
                if (start < path.length())
                {
                    dirs.push_back(path.substr(start));
                }
                break;
            }
        }
    }

    // Create path recursively
    subpath = "";
    for (int i = 0; i < dirs.size(); ++i)
    {
        subpath += dirs[i];
        DIR *dir = opendir(subpath.c_str());

        if (!dir)
        {
            // directory doesn't exist, should create a new one

            int ret = mkdir(subpath.c_str(), S_IRWXU | S_IRWXG | S_IRWXO);
            if (ret != 0 && (errno != EEXIST))
            {
                // current directory can not be created, sub directories can not be created too
                // should return
                return false;
            }
        }
        else
        {
            // directory exists, should close opened dir
            closedir(dir);
        }
    }
    return true;
}
Ejemplo n.º 2
0
bool KDirectory::createDir(const KData& dir)
{
	int pos = 0;
	while (true)
	{
		if ((pos = dir.find("/", pos)) == -1)
			pos = dir.length();
		KData dtDir = dir.substr(0, pos);
		pos++;
		if (!dtDir.isEmpty())
		{
			if (!isDirectoryExist(dtDir))
			{
				/*
				 if ( -1 == mkdir(dtDir.getData(),S_IRWXU|S_IRWXG|S_IRWXO) )
				 {
				 return false;
				 }
				 */
				if (MKDIR(dtDir.getData()) != 0)
				{
					return false;
				}

			}
		}
		if (pos >= (int) dir.length())
			break;
	}
	return true;
}
Ejemplo n.º 3
0
/*
 bool KDirectory::isDirEmpty( const KData& fullDir )
 {
 KData dtDir = fullDir;
 dtDir.makePath( true );
 DIR* dir;
 if ( (dir=opendir(dtDir.getData())) == NULL )
 return false;
 struct dirent *pDirent;
 while( ( pDirent = readdir(dir) ) != NULL  )
 {
 struct stat statbuf;
 KData dtPath = dtDir;
 dtPath += pDirent->d_name;
 if ( stat(dtPath.getData(),&statbuf) == -1 )
 continue;
 if ( S_ISDIR(statbuf.st_mode) )
 {
 if ( pDirent->d_name && strcmp(pDirent->d_name,".") && strcmp(pDirent->d_name,"..") )
 {
 if ( !isDirEmpty(dtPath) )
 {
 closedir( dir );
 return false;
 }
 }
 }
 else
 {
 closedir( dir );
 return false;
 }
 }
 closedir( dir );
 return true;

 }
 */
bool KDirectory::open(const KData& directory, bool create)
{
	if (directory.isEmpty())
	{
		return false;
	}

	KData dir = directory;
	int pos;
	KData dtKData = "\\";
	while ((pos = dir.find(dtKData)) != -1)
	{
		dir.replace(pos, 1, "/");
	}
	_directory.erase();

	bool bDirExist = isDirectoryExist(dir);
	if (!bDirExist)
	{
		if (create)
		{
			if (!createDir(dir))
				return false;
		}
		else
		{
			return false;
		}
	}
	_directory = dir;
	_directory.makePath();
	return true;
}
Ejemplo n.º 4
0
bool KDirectory::createFileDir(const KData& dir)
{
	int pos = 0;
	while (true)
	{
		if ((pos = dir.find("/", pos)) == -1)
			break;
		KData dtDir = dir.substr(0, pos);
		pos++;
		if (!dtDir.isEmpty())
		{
			if (!isDirectoryExist(dtDir))
			{
				if (MKDIR(dtDir.getData()) != 0)
				{
					return false;
				}
			}
		}
	}
	return true;
}
bool FileUtils::createDirectory(const std::string& path)
{
    CCASSERT(!path.empty(), "Invalid path");

    if (isDirectoryExist(path))
        return true;

    // Split the path
    size_t start = 0;
    size_t found = path.find_first_of("/\\", start);
    std::string subpath;
    std::vector<std::string> dirs;

    if (found != std::string::npos)
    {
        while (true)
        {
            subpath = path.substr(start, found - start + 1);
            if (!subpath.empty())
                dirs.push_back(subpath);
            start = found+1;
            found = path.find_first_of("/\\", start);
            if (found == std::string::npos)
            {
                if (start < path.length())
                {
                    dirs.push_back(path.substr(start));
                }
                break;
            }
        }
    }


#if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
    WIN32_FILE_ATTRIBUTE_DATA wfad;
    std::wstring wpath(path.begin(), path.end());
    if (!(GetFileAttributesEx(wpath.c_str(), GetFileExInfoStandard, &wfad)))
    {
        subpath = "";
        for(unsigned int i = 0 ; i < dirs.size() ; ++i)
        {
            subpath += dirs[i];
            if (i > 0 && !isDirectoryExist(subpath))
            {
                std::wstring wsubpath(subpath.begin(), subpath.end());
                BOOL ret = CreateDirectory(wsubpath.c_str(), NULL);
                if (!ret && ERROR_ALREADY_EXISTS != GetLastError())
                {
                    return false;
                }
            }
        }
    }
    return true;
#elif (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
    if ((GetFileAttributesA(path.c_str())) == INVALID_FILE_ATTRIBUTES)
    {
        subpath = "";
        for (int i = 0; i < dirs.size(); ++i)
        {
            subpath += dirs[i];
            if (!isDirectoryExist(subpath))
            {
                BOOL ret = CreateDirectoryA(subpath.c_str(), NULL);
                if (!ret && ERROR_ALREADY_EXISTS != GetLastError())
                {
                    return false;
                }
            }
        }
    }
    return true;
#else
    DIR *dir = NULL;

    // Create path recursively
    subpath = "";
    for (int i = 0; i < dirs.size(); ++i)
    {
        subpath += dirs[i];
        dir = opendir(subpath.c_str());

        if (!dir)
        {
            // directory doesn't exist, should create a new one

            int ret = mkdir(subpath.c_str(), S_IRWXU | S_IRWXG | S_IRWXO);
            if (ret != 0 && (errno != EEXIST))
            {
                // current directory can not be created, sub directories can not be created too
                // should return
                return false;
            }
        }
        else
        {
            // directory exists, should close opened dir
            closedir(dir);
        }
    }
    return true;
#endif
}
Ejemplo n.º 6
0
void TestUnicodePath::onEnter()
{
    FileUtilsDemo::onEnter();
    auto s = Director::getInstance()->getWinSize();
    auto util = FileUtils::getInstance();
    
    int x = s.width/2,
    y = s.height/5;
    Label* label = nullptr;
    
    std::string dir = "中文路径/";
    std::string filename = "测试文件.test";

    std::string act;
    auto getMsg = [&act](bool b, const std::string& path)-> std::string
    {
        char msg[512];
        snprintf((char *)msg, 512, "%s for %s path: \"%s\"", b ? "success" : "failed", act.c_str(), path.c_str());
        return std::string(msg);
    };
    
    // Check whether unicode dir should be create or not
    std::string dirPath = util->getWritablePath() + dir;
    if (!util->isDirectoryExist(dirPath))
    {
        util->createDirectory(dirPath);
    }
    
    act = "create";
    bool isExist = util->isDirectoryExist(dirPath);
    label = Label::createWithSystemFont(getMsg(isExist, dirPath), "", 12, Size(s.width, 0));
    label->setPosition(x, y * 4);
    this->addChild(label);
    
    if (isExist)
    {
        // Check whether unicode file should be create or not
        std::string filePath = dirPath + filename;
        if (! util->isFileExist(filePath))
        {
            std::string writeDataStr = " 测试字符串.";
            Data writeData;
            writeData.copy((unsigned char *)writeDataStr.c_str(), writeDataStr.size());
            util->writeDataToFile(writeData, filePath);
        }
        
        isExist = util->isFileExist(filePath);
        label = Label::createWithSystemFont(getMsg(isExist, filePath), "", 12, Size(s.width, 0));
        label->setPosition(x, y * 3);
        this->addChild(label);
        
        act = "remove";
        if (isExist)
        {
            // read file content and log it
            unsigned char* buffer = nullptr;
            Data readData = util->getDataFromFile(filePath);
            buffer = (unsigned char*)malloc(sizeof(unsigned char) * (readData.getSize() + 1));
            memcpy(buffer, readData.getBytes(), readData.getSize());
            buffer[readData.getSize()] = '\0';
            // vc can't treat unicode string correctly, don't use unicode string in code
            log("The content of file from writable path: %s", buffer);
            free(buffer);
            
            // remove test file
            label = Label::createWithSystemFont(getMsg(util->removeFile(filePath), filePath), "", 12, Size(s.width, 0));
            label->setPosition(x, y * 2);
            this->addChild(label);
        }
        
        // remove test dir
        label = Label::createWithSystemFont(getMsg(util->removeDirectory(dirPath), dirPath), "", 12, Size(s.width, 0));
        label->setPosition(x, y * 1);
        this->addChild(label);
    }
}
Ejemplo n.º 7
0
void TestDirectoryFuncs::onEnter()
{
    FileUtilsDemo::onEnter();
    auto s = Director::getInstance()->getWinSize();
    auto sharedFileUtils = FileUtils::getInstance();

    int x = s.width/2,
    y = s.height/4;
    Label* label = nullptr;

    std::string dir = sharedFileUtils->getWritablePath() + "__test/";
    std::string subDir = "dir1/dir2";
    std::string msg;
    bool ok;

    // Check whether dir can be created
    ok = sharedFileUtils->createDirectory(dir);
    if (ok && sharedFileUtils->isDirectoryExist(dir))
    {
        msg = StringUtils::format("createDirectory: Directory '__test' created");
        label = Label::createWithSystemFont(msg, "", 20);
        label->setPosition(x, y * 3);
        this->addChild(label);

        // Create sub directories recursively
        ok = sharedFileUtils->createDirectory(dir + subDir);
        if (ok && sharedFileUtils->isDirectoryExist(dir + subDir))
        {
            msg = StringUtils::format("createDirectory: Sub directories '%s' created", subDir.c_str());
            label = Label::createWithSystemFont(msg, "", 20);
            label->setPosition(x, y * 2);
            this->addChild(label);
        }
        else
        {
            msg = StringUtils::format("createDirectory: Failed to create sub directories '%s'", subDir.c_str());
            label = Label::createWithSystemFont(msg, "", 20);
            label->setPosition(x, y * 2);
            this->addChild(label);
        }

        // Remove directory
        ok = sharedFileUtils->removeDirectory(dir);
        if (ok && !sharedFileUtils->isDirectoryExist(dir))
        {
            msg = StringUtils::format("removeDirectory: Directory '__test' removed");
            label = Label::createWithSystemFont(msg, "", 20);
            label->setPosition(x, y);
            this->addChild(label);
        }
        else
        {
            msg = StringUtils::format("removeDirectory: Failed to remove directory '__test'");
            label = Label::createWithSystemFont(msg, "", 20);
            label->setPosition(x, y);
            this->addChild(label);
        }
    }
    else
    {
        msg = StringUtils::format("createDirectory: Directory '__test' can not be created");
        label = Label::createWithSystemFont(msg, "", 20);
        label->setPosition(x, y * 2);
        this->addChild(label);
    }
}
Ejemplo n.º 8
0
//释放文件
bool CCZipFile::extract_ex(std::string& root,int handler)
{
    bool flag = false;
    auto fs = CCFileUtils::sharedFileUtils();
    do{
        if(root.empty()) {
            break;
        }
        auto len = root.length();
        if(root[0]!='/'){
            break;
        }
        if(root[len-1]!='/'){
            root+='/';
        }
        if(!fs->isDirectoryExist(root)){
            if(!fs->createDirectory(root)){
                break;
            }
        }
        if(!m_hasGenFlist)
        {
            genFileList();
        }
        int ct = 0; 
        int max = m_fileList.size();
        for(auto ff:m_fileList)
        {
            auto & name = ff.first;
            auto ll = name.length();
            if(name[ll-1]=='/')
            {
                ct++;
                if(!fs->createDirectory(root+name)){
                    break;
                }
                continue;
            }
            unsigned long sz = 0;
            unsigned char* data = this->getFileDataNoOrder(name.c_str(),&sz);
            if(data)
            {
                auto f = fs->writeToFile(root+name, data, (unsigned int)sz);
                if(!f) {
                    CCLOG("extract fail to writeToFile %s",name.c_str());
                    break;
                }
            }
            else{
                CCLOG("extract fail to getFileDataNoOrder %s",name.c_str());
                break;
            }
            ct++;
            if(handler && ct%30==0)
            {
                 CCDirector::sharedDirector()->getScheduler()->performFunctionInCocosThread([this,ct,max,handler](){
                        cocos2d::CCLuaEngine* luaEngine = cocos2d::CCLuaEngine::defaultEngine();
                        cocos2d::CCLuaStack *pStack = luaEngine->getLuaStack();
                        pStack->pushInt(1);
                        pStack->pushInt(max);
                        pStack->pushInt(ct);
                        pStack->executeFunctionByHandler(handler,3);
                        pStack->clean();
                 });
                std::this_thread::sleep_for(std::chrono::milliseconds(20));
            }
        }
        flag = true;
    }while(0);
    return flag;
}