Restructure CCFileUtils class, move platform related functions to CCFileUtilsXXX.

Add TestIsDirectoryExist and TestUnicodePath in cpp-tests FileUtil test.
This commit is contained in:
Vincent Yang 2015-07-14 09:44:36 +08:00
commit 0589c14302
14 changed files with 716 additions and 370 deletions

File diff suppressed because it is too large Load Diff

View File

@ -497,7 +497,7 @@ protected:
* @param dirPath The directory (with absolute path) to look up for
* @return Returns true if the directory found at the given absolute path, otherwise returns false
*/
virtual bool isDirectoryExistInternal(const std::string& dirPath) const = 0;
virtual bool isDirectoryExistInternal(const std::string& dirPath) const;
/**
* Gets full path for filename, resolution directory and search path.

View File

@ -57,7 +57,8 @@ public:
void setBundle(NSBundle* bundle);
private:
virtual bool isFileExistInternal(const std::string& filePath) const override;
virtual bool isDirectoryExistInternal(const std::string& dirPath) const override;
virtual bool removeDirectory(const std::string& dirPath) override;
NSBundle* getBundle() const;
NSBundle* _bundle;
};

View File

@ -394,14 +394,29 @@ bool FileUtilsApple::isFileExistInternal(const std::string& filePath) const
return ret;
}
bool FileUtilsApple::isDirectoryExistInternal(const std::string& dirPath) const
static int unlink_cb(const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf)
{
struct stat st;
if (stat(dirPath.c_str(), &st) == 0)
auto ret = remove(fpath);
if (ret)
{
return S_ISDIR(st.st_mode);
log("Fail to remove: %s ",fpath);
}
return false;
return ret;
}
bool FileUtilsApple::removeDirectory(const std::string& path)
{
if (path.size() > 0 && path[path.size() - 1] != '/')
{
CCLOGERROR("Fail to remove directory, path must termniate with '/': %s", path.c_str());
return false;
}
if (nftw(path.c_str(),unlink_cb, 64, FTW_DEPTH | FTW_PHYS))
return false;
else
return true;
}
std::string FileUtilsApple::getFullPathForDirectoryAndFilename(const std::string& directory, const std::string& filename) const

View File

@ -122,16 +122,6 @@ bool FileUtilsLinux::isFileExistInternal(const std::string& strFilePath) const
return (stat(strPath.c_str(), &sts) != -1) ? true : false;
}
bool FileUtilsLinux::isDirectoryExistInternal(const std::string& dirPath) const
{
struct stat st;
if (stat(dirPath.c_str(), &st) == 0)
{
return S_ISDIR(st.st_mode);
}
return false;
}
NS_CC_END
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_LINUX

View File

@ -53,7 +53,6 @@ public:
virtual std::string getWritablePath() const;
private:
virtual bool isFileExistInternal(const std::string& strFilePath) const override;
virtual bool isDirectoryExistInternal(const std::string& dirPath) const override;
};
// end of platform group

View File

@ -106,6 +106,32 @@ static std::string StringWideCharToUtf8(const std::wstring& strWideChar)
return ret;
}
static std::string UTF8StringToMultiByte(const std::string& strUtf8)
{
std::string ret;
if (!strUtf8.empty())
{
std::wstring strWideChar = StringUtf8ToWideChar(strUtf8);
int nNum = WideCharToMultiByte(CP_ACP, 0, strWideChar.c_str(), -1, nullptr, 0, nullptr, FALSE);
if (nNum)
{
char* ansiString = new char[nNum + 1];
ansiString[0] = 0;
nNum = WideCharToMultiByte(CP_ACP, 0, strWideChar.c_str(), -1, ansiString, nNum + 1, nullptr, FALSE);
ret = ansiString;
delete[] ansiString;
}
else
{
CCLOG("Wrong convert to Ansi code:0x%x", GetLastError());
}
}
return ret;
}
static void _checkPath()
{
if (0 == s_resourcePath.length())
@ -160,6 +186,11 @@ bool FileUtilsWin32::isDirectoryExistInternal(const std::string& dirPath) const
return false;
}
std::string FileUtilsWin32::getSuitableFOpen(const std::string& filenameUtf8) const
{
return UTF8StringToMultiByte(filenameUtf8);
}
bool FileUtilsWin32::isFileExistInternal(const std::string& strFilePath) const
{
if (0 == strFilePath.length())
@ -179,17 +210,6 @@ bool FileUtilsWin32::isFileExistInternal(const std::string& strFilePath) const
return true;
}
bool FileUtilsWin32::isDirectoryExistInternal(const std::string& dirPath) const
{
unsigned long fAttrib = GetFileAttributesA(dirPath.c_str());
if (fAttrib != INVALID_FILE_ATTRIBUTES &&
(fAttrib & FILE_ATTRIBUTE_DIRECTORY))
{
return true;
}
return false;
}
bool FileUtilsWin32::isAbsolutePath(const std::string& strPath) const
{
if ( (strPath.length() > 2

View File

@ -51,6 +51,7 @@ public:
bool init();
virtual std::string getWritablePath() const override;
virtual bool isAbsolutePath(const std::string& strPath) const override;
virtual std::string getSuitableFOpen(const std::string& filenameUtf8) const override;
protected:
virtual bool isFileExistInternal(const std::string& strFilePath) const override;
@ -105,7 +106,7 @@ protected:
* @return Upon success, a pointer to the data is returned, otherwise NULL.
* @warning Recall: you are responsible for calling delete[] on any Non-NULL pointer returned.
*/
virtual unsigned char* getFileData(const std::string& filename, const char* mode, ssize_t * size) override;
CC_DEPRECATED_ATTRIBUTE virtual unsigned char* getFileData(const std::string& filename, const char* mode, ssize_t * size) override;
/**
* Gets string from a file.

View File

@ -23,9 +23,9 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "CCFileUtilsWinRT.h"
#include <regex>
#include "CCWinRTUtils.h"
#include "platform/CCCommon.h"
using namespace std;
NS_CC_BEGIN
@ -47,6 +47,80 @@ static inline std::string convertPathFormatToUnixStyle(const std::string& path)
return ret;
}
static std::wstring StringUtf8ToWideChar(const std::string& strUtf8)
{
std::wstring ret;
if (!strUtf8.empty())
{
int nNum = MultiByteToWideChar(CP_UTF8, 0, strUtf8.c_str(), -1, nullptr, 0);
if (nNum)
{
WCHAR* wideCharString = new WCHAR[nNum + 1];
wideCharString[0] = 0;
nNum = MultiByteToWideChar(CP_UTF8, 0, strUtf8.c_str(), -1, wideCharString, nNum + 1);
ret = wideCharString;
delete[] wideCharString;
}
else
{
CCLOG("Wrong convert to WideChar code:0x%x", GetLastError());
}
}
return ret;
}
static std::string StringWideCharToUtf8(const std::wstring& strWideChar)
{
std::string ret;
if (!strWideChar.empty())
{
int nNum = WideCharToMultiByte(CP_UTF8, 0, strWideChar.c_str(), -1, nullptr, 0, nullptr, FALSE);
if (nNum)
{
char* utf8String = new char[nNum + 1];
utf8String[0] = 0;
nNum = WideCharToMultiByte(CP_UTF8, 0, strWideChar.c_str(), -1, utf8String, nNum + 1, nullptr, FALSE);
ret = utf8String;
delete[] utf8String;
}
else
{
CCLOG("Wrong convert to Utf8 code:0x%x", GetLastError());
}
}
return ret;
}
static std::string UTF8StringToMultiByte(const std::string& strUtf8)
{
std::string ret;
if (!strUtf8.empty())
{
std::wstring strWideChar = StringUtf8ToWideChar(strUtf8);
int nNum = WideCharToMultiByte(CP_ACP, 0, strWideChar.c_str(), -1, nullptr, 0, nullptr, FALSE);
if (nNum)
{
char* ansiString = new char[nNum + 1];
ansiString[0] = 0;
nNum = WideCharToMultiByte(CP_ACP, 0, strWideChar.c_str(), -1, ansiString, nNum + 1, nullptr, FALSE);
ret = ansiString;
delete[] ansiString;
}
else
{
CCLOG("Wrong convert to Ansi code:0x%x", GetLastError());
}
}
return ret;
}
static void _checkPath()
{
@ -72,7 +146,6 @@ FileUtils* FileUtils::getInstance()
return s_sharedFileUtils;
}
CCFileUtilsWinRT::CCFileUtilsWinRT()
{
}
@ -100,6 +173,11 @@ std::string CCFileUtilsWinRT::getFullPathForDirectoryAndFilename(const std::stri
return FileUtils::getFullPathForDirectoryAndFilename(unixDirectory, unixFilename);
}
std::string CCFileUtilsWinRT::getSuitableFOpen(const std::string& filenameUtf8) const
{
return UTF8StringToMultiByte(filenameUtf8);
}
bool CCFileUtilsWinRT::isFileExistInternal(const std::string& strFilePath) const
{
bool ret = false;
@ -132,6 +210,99 @@ bool CCFileUtilsWinRT::isDirectoryExistInternal(const std::string& dirPath) cons
return false;
}
bool CCFileUtilsWinRT::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;
}
}
}
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;
}
bool CCFileUtilsWinRT::removeDirectory(const std::string& path)
{
std::wstring wpath = std::wstring(path.begin(), path.end());
std::wstring files = wpath + L"*.*";
WIN32_FIND_DATA wfd;
HANDLE search = FindFirstFileEx(files.c_str(), FindExInfoStandard, &wfd, FindExSearchNameMatch, NULL, 0);
bool ret = true;
if (search != INVALID_HANDLE_VALUE)
{
BOOL find = true;
while (find)
{
//. ..
if (wfd.cFileName[0] != '.')
{
std::wstring temp = wpath + wfd.cFileName;
if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
temp += '/';
ret = ret && this->removeDirectory(std::string(temp.begin(), temp.end()));
}
else
{
SetFileAttributes(temp.c_str(), FILE_ATTRIBUTE_NORMAL);
ret = ret && DeleteFile(temp.c_str());
}
}
find = FindNextFile(search, &wfd);
}
FindClose(search);
}
if (ret && RemoveDirectory(wpath.c_str()))
{
return true;
}
return false;
}
bool CCFileUtilsWinRT::isAbsolutePath(const std::string& strPath) const
{
if ( strPath.length() > 2
@ -143,6 +314,34 @@ bool CCFileUtilsWinRT::isAbsolutePath(const std::string& strPath) const
return false;
}
bool CCFileUtilsWinRT::removeFile(const std::string &path)
{
std::wstring wpath(path.begin(), path.end());
if (DeleteFile(wpath.c_str()))
{
return true;
}
return false;
}
bool CCFileUtilsWinRT::renameFile(const std::string &path, const std::string &oldname, const std::string &name)
{
CCASSERT(!path.empty(), "Invalid path");
std::string oldPath = path + oldname;
std::string newPath = path + name;
std::regex pat("\\/");
std::string _old = std::regex_replace(oldPath, pat, "\\");
std::string _new = std::regex_replace(newPath, pat, "\\");
if (MoveFileEx(std::wstring(_old.begin(), _old.end()).c_str(),
std::wstring(_new.begin(), _new.end()).c_str(),
MOVEFILE_REPLACE_EXISTING & MOVEFILE_WRITE_THROUGH))
{
return true;
}
return false;
}
static Data getData(const std::string& filename, bool forString)
{
if (filename.empty())

View File

@ -49,14 +49,55 @@ public:
bool init();
virtual std::string getWritablePath() const;
virtual bool isAbsolutePath(const std::string& strPath) const;
virtual std::string getPathForFilename(const std::string& filename, const std::string& resolutionDirectory, const std::string& searchPath) const override;
virtual std::string getPathForFilename(const std::string& filename, const std::string& resolutionDirectory, const std::string& searchPath) const override;
virtual std::string getFullPathForDirectoryAndFilename(const std::string& strDirectory, const std::string& strFilename) const override;
virtual std::string getStringFromFile(const std::string& filename) override;
virtual std::string getSuitableFOpen(const std::string& filenameUtf8) const override;
static std::string getAppPath();
private:
virtual bool isFileExistInternal(const std::string& strFilePath) const override;
/**
* Renames a file under the given directory.
*
* @param path The parent directory path of the file, it must be an absolute path.
* @param oldname The current name of the file.
* @param name The new name of the file.
* @return True if the file have been renamed successfully, false if not.
*/
virtual bool renameFile(const std::string &path, const std::string &oldname, const std::string &name) override;
/**
* Checks whether a directory exists without considering search paths and resolution orders.
* @param dirPath The directory (with absolute path) to look up for
* @return Returns true if the directory found at the given absolute path, otherwise returns false
*/
virtual bool isDirectoryExistInternal(const std::string& dirPath) const override;
/**
* Removes a file.
*
* @param filepath The full path of the file, it must be an absolute path.
* @return True if the file have been removed successfully, false if not.
*/
virtual bool removeFile(const std::string &filepath) override;
/**
* Creates a directory.
*
* @param dirPath The path of the directory, it must be an absolute path.
* @return True if the directory have been created successfully, false if not.
*/
virtual bool createDirectory(const std::string& dirPath) override;
/**
* Removes a directory.
*
* @param dirPath The full path of the directory, it must be an absolute path.
* @return True if the directory have been removed successfully, false if not.
*/
virtual bool removeDirectory(const std::string& dirPath) override;
};
// end of platform group

View File

@ -8,6 +8,7 @@ FileUtilsTests::FileUtilsTests()
ADD_TEST_CASE(TestSearchPath);
ADD_TEST_CASE(TestFilenameLookup);
ADD_TEST_CASE(TestIsFileExist);
ADD_TEST_CASE(TestIsDirectoryExist);
ADD_TEST_CASE(TestFileFuncs);
ADD_TEST_CASE(TestDirectoryFuncs);
ADD_TEST_CASE(TextWritePlist);
@ -15,6 +16,7 @@ FileUtilsTests::FileUtilsTests()
ADD_TEST_CASE(TestWriteData);
ADD_TEST_CASE(TestWriteValueMap);
ADD_TEST_CASE(TestWriteValueVector);
ADD_TEST_CASE(TestUnicodePath);
}
// TestResolutionDirectories
@ -122,7 +124,7 @@ void TestSearchPath::onEnter()
if (fp)
{
char szReadBuf[100] = {0};
size_t read = fread(szReadBuf, 1, strlen(szBuf), fp);
size_t read = fread(szReadBuf, 1, strlen(szReadBuf), fp);
if (read > 0)
log("The content of file from writable path: %s", szReadBuf);
fclose(fp);
@ -232,6 +234,61 @@ std::string TestIsFileExist::subtitle() const
return "";
}
// TestIsDirectoryExist
void TestIsDirectoryExist::onEnter()
{
FileUtilsDemo::onEnter();
auto s = Director::getInstance()->getWinSize();
auto util = FileUtils::getInstance();
int x = s.width/2, y = s.height/3;
Label* label = nullptr;
std::string dir;
char msg[512];
auto getMsg = [&dir, &msg](bool b)->const char *
{
snprintf((char *)msg, 512, "%s for dir: \"%s\"", b ? "success" : "failed", dir.c_str());
return msg;
};
dir = "Images";
label = Label::createWithSystemFont(getMsg(util->isDirectoryExist(dir)), "", 20);
label->setPosition(x, y * 2);
this->addChild(label);
dir = util->getWritablePath();
label = Label::createWithSystemFont(getMsg(util->isDirectoryExist(dir)), "", 20);
label->setPosition(x, y * 1);
this->addChild(label);
dir = util->getWritablePath();
label = Label::createWithSystemFont(getMsg(util->isDirectoryExist(dir)), "", 20);
label->setPosition(x, y * 1);
this->addChild(label);
}
void TestIsDirectoryExist::onExit()
{
FileUtils *sharedFileUtils = FileUtils::getInstance();
// reset filename lookup
sharedFileUtils->purgeCachedEntries();
FileUtilsDemo::onExit();
}
std::string TestIsDirectoryExist::title() const
{
return "FileUtils: check whether the directory exists";
}
std::string TestIsDirectoryExist::subtitle() const
{
return "";
}
// TestFileFuncs
void TestFileFuncs::onEnter()
@ -801,3 +858,101 @@ std::string TestWriteValueVector::subtitle() const
{
return "";
}
// TestUnicodePath
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;
char msg[512];
auto getMsg = [&act, &msg](bool b, const std::string& path)->const char *
{
snprintf((char *)msg, 512, "%s for %s path: \"%s\"", b ? "success" : "failed", act.c_str(), path.c_str());
return 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);
}
}
void TestUnicodePath::onExit()
{
FileUtils *sharedFileUtils = FileUtils::getInstance();
sharedFileUtils->purgeCachedEntries();
sharedFileUtils->setFilenameLookupDictionary(ValueMap());
FileUtilsDemo::onExit();
}
std::string TestUnicodePath::title() const
{
return "FileUtils: check unicode path";
}
std::string TestUnicodePath::subtitle() const
{
return "";
}

View File

@ -60,6 +60,17 @@ public:
virtual std::string subtitle() const override;
};
class TestIsDirectoryExist : public FileUtilsDemo
{
public:
CREATE_FUNC(TestIsDirectoryExist);
virtual void onEnter() override;
virtual void onExit() override;
virtual std::string title() const override;
virtual std::string subtitle() const override;
};
class TestFileFuncs : public FileUtilsDemo
{
public:
@ -134,4 +145,16 @@ public:
virtual std::string title() const override;
virtual std::string subtitle() const override;
};
class TestUnicodePath : public FileUtilsDemo
{
public:
CREATE_FUNC(TestUnicodePath);
virtual void onEnter() override;
virtual void onExit() override;
virtual std::string title() const override;
virtual std::string subtitle() const override;
};
#endif /* __FILEUTILSTEST_H__ */

View File

@ -95,6 +95,7 @@ LOCAL_SRC_FILES := main.cpp \
../../../Classes/NewAudioEngineTest/NewAudioEngineTest.cpp \
../../../Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp \
../../../Classes/NewRendererTest/NewRendererTest.cpp \
../../../Classes/NavMeshTest/NavMeshTest.cpp \
../../../Classes/NodeTest/NodeTest.cpp \
../../../Classes/OpenURLTest/OpenURLTest.cpp \
../../../Classes/ParallaxTest/ParallaxTest.cpp \
@ -201,10 +202,10 @@ LOCAL_SRC_FILES := main.cpp \
../../../Classes/UnitTest/UnitTest.cpp \
../../../Classes/UserDefaultTest/UserDefaultTest.cpp \
../../../Classes/VisibleRect.cpp \
../../../Classes/VibrateTest/VibrateTest.cpp \
../../../Classes/ZwoptexTest/ZwoptexTest.cpp \
../../../Classes/controller.cpp \
../../../Classes/testBasic.cpp \
../../../Classes/NavMeshTest/NavMeshTest.cpp
../../../Classes/testBasic.cpp
LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../../Classes \
$(LOCAL_PATH)/../../../../..

View File

@ -799,6 +799,7 @@
<ClCompile Include="$(MSBuildThisFileDirectory)..\..\Classes\NavMeshTest\NavMeshTest.cpp">
<Filter>Classes\NavMeshTest</Filter>
</ClCompile>
<ClCompile Include="$(MSBuildThisFileDirectory)..\..\Classes\UITest\CocoStudioGUITest\UIRadioButtonTest\UIRadioButtonTest.cpp" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="$(MSBuildThisFileDirectory)..\..\Classes\ActionManagerTest\ActionManagerTest.cpp">
@ -1260,9 +1261,6 @@
<ClCompile Include="$(MSBuildThisFileDirectory)..\..\Classes\UITest\CocoStudioGUITest\UICheckBoxTest\UICheckBoxTest_Editor.cpp">
<Filter>Classes\UITest\CocostudioGUISceneTest\UICheckBoxTest</Filter>
</ClCompile>
<ClCompile Include="$(MSBuildThisFileDirectory)..\..\Classes\UITest\CocoStudioGUITest\UIRadioButtonTest\UIRadioButtonTest.cpp">
<Filter>Classes\UITest\CocostudioGUISceneTest\UIRadioButtonTest</Filter>
</ClCompile>
<ClCompile Include="$(MSBuildThisFileDirectory)..\..\Classes\UITest\CocoStudioGUITest\UIFocusTest\UIFocusTest.cpp">
<Filter>Classes\UITest\CocostudioGUISceneTest\UIFocusTest</Filter>
</ClCompile>
@ -1780,4 +1778,4 @@
<Filter>Classes\NavMeshTest</Filter>
</ClInclude>
</ItemGroup>
</Project>
</Project>