Merge pr11866: FileUtilsWin32 correct use all unicode version winapi.

This commit is contained in:
Vincent Yang 2015-07-14 09:35:01 +08:00
commit 06bf6ffa90
3 changed files with 471 additions and 335 deletions

View File

@ -81,17 +81,17 @@ class DictMaker : public SAXDelegator
{ {
public: public:
SAXResult _resultType; SAXResult _resultType;
ValueMap _rootDict; ValueMap _rootDict;
ValueVector _rootArray; ValueVector _rootArray;
std::string _curKey; ///< parsed key std::string _curKey; ///< parsed key
std::string _curValue; // parsed value std::string _curValue; // parsed value
SAXState _state; SAXState _state;
ValueMap* _curDict; ValueMap* _curDict;
ValueVector* _curArray; ValueVector* _curArray;
std::stack<ValueMap*> _dictStack; std::stack<ValueMap*> _dictStack;
std::stack<ValueVector*> _arrayStack; std::stack<ValueVector*> _arrayStack;
std::stack<SAXState> _stateStack; std::stack<SAXState> _stateStack;
@ -114,20 +114,20 @@ public:
parser.setDelegator(this); parser.setDelegator(this);
parser.parse(fileName); parser.parse(fileName);
return _rootDict; return _rootDict;
} }
ValueMap dictionaryWithDataOfFile(const char* filedata, int filesize) ValueMap dictionaryWithDataOfFile(const char* filedata, int filesize)
{ {
_resultType = SAX_RESULT_DICT; _resultType = SAX_RESULT_DICT;
SAXParser parser; SAXParser parser;
CCASSERT(parser.init("UTF-8"), "The file format isn't UTF-8"); CCASSERT(parser.init("UTF-8"), "The file format isn't UTF-8");
parser.setDelegator(this); parser.setDelegator(this);
parser.parse(filedata, filesize); parser.parse(filedata, filesize);
return _rootDict; return _rootDict;
} }
ValueVector arrayWithContentsOfFile(const std::string& fileName) ValueVector arrayWithContentsOfFile(const std::string& fileName)
{ {
@ -138,7 +138,7 @@ public:
parser.setDelegator(this); parser.setDelegator(this);
parser.parse(fileName); parser.parse(fileName);
return _rootArray; return _rootArray;
} }
void startElement(void *ctx, const char *name, const char **atts) void startElement(void *ctx, const char *name, const char **atts)
@ -148,7 +148,7 @@ public:
const std::string sName(name); const std::string sName(name);
if( sName == "dict" ) if( sName == "dict" )
{ {
if(_resultType == SAX_RESULT_DICT && _rootDict.empty()) if(_resultType == SAX_RESULT_DICT && _rootDict.empty())
{ {
_curDict = &_rootDict; _curDict = &_rootDict;
} }
@ -165,7 +165,7 @@ public:
{ {
// add a new dictionary into the array // add a new dictionary into the array
_curArray->push_back(Value(ValueMap())); _curArray->push_back(Value(ValueMap()));
_curDict = &(_curArray->rbegin())->asValueMap(); _curDict = &(_curArray->rbegin())->asValueMap();
} }
else if (SAX_DICT == preState) else if (SAX_DICT == preState)
{ {
@ -173,7 +173,7 @@ public:
CCASSERT(! _dictStack.empty(), "The state is wrong!"); CCASSERT(! _dictStack.empty(), "The state is wrong!");
ValueMap* preDict = _dictStack.top(); ValueMap* preDict = _dictStack.top();
(*preDict)[_curKey] = Value(ValueMap()); (*preDict)[_curKey] = Value(ValueMap());
_curDict = &(*preDict)[_curKey].asValueMap(); _curDict = &(*preDict)[_curKey].asValueMap();
} }
// record the dict state // record the dict state
@ -200,9 +200,9 @@ public:
{ {
_state = SAX_ARRAY; _state = SAX_ARRAY;
if (_resultType == SAX_RESULT_ARRAY && _rootArray.empty()) if (_resultType == SAX_RESULT_ARRAY && _rootArray.empty())
{ {
_curArray = &_rootArray; _curArray = &_rootArray;
} }
SAXState preState = SAX_NONE; SAXState preState = SAX_NONE;
if (! _stateStack.empty()) if (! _stateStack.empty())
@ -213,14 +213,14 @@ public:
if (preState == SAX_DICT) if (preState == SAX_DICT)
{ {
(*_curDict)[_curKey] = Value(ValueVector()); (*_curDict)[_curKey] = Value(ValueVector());
_curArray = &(*_curDict)[_curKey].asValueVector(); _curArray = &(*_curDict)[_curKey].asValueVector();
} }
else if (preState == SAX_ARRAY) else if (preState == SAX_ARRAY)
{ {
CCASSERT(! _arrayStack.empty(), "The state is wrong!"); CCASSERT(! _arrayStack.empty(), "The state is wrong!");
ValueVector* preArray = _arrayStack.top(); ValueVector* preArray = _arrayStack.top();
preArray->push_back(Value(ValueVector())); preArray->push_back(Value(ValueVector()));
_curArray = &(_curArray->rbegin())->asValueVector(); _curArray = &(_curArray->rbegin())->asValueVector();
} }
// record the array state // record the array state
_stateStack.push(_state); _stateStack.push(_state);
@ -370,12 +370,8 @@ static tinyxml2::XMLElement* generateElementForDict(const ValueMap& dict, tinyxm
*/ */
bool FileUtils::writeToFile(ValueMap& dict, const std::string &fullPath) bool FileUtils::writeToFile(ValueMap& dict, const std::string &fullPath)
{ {
return writeValueMapToFile(dict, fullPath); //CCLOG("tinyxml2 Dictionary %d writeToFile %s", dict->_ID, fullPath.c_str());
} tinyxml2::XMLDocument *doc = new tinyxml2::XMLDocument();
bool FileUtils::writeValueMapToFile(ValueMap& dict, const std::string& fullPath)
{
tinyxml2::XMLDocument *doc = new (std::nothrow)tinyxml2::XMLDocument();
if (nullptr == doc) if (nullptr == doc)
return false; return false;
@ -400,47 +396,7 @@ bool FileUtils::writeValueMapToFile(ValueMap& dict, const std::string& fullPath)
doc->LinkEndChild(rootEle); doc->LinkEndChild(rootEle);
tinyxml2::XMLElement *innerDict = generateElementForDict(dict, doc); tinyxml2::XMLElement *innerDict = generateElementForDict(dict, doc);
if (nullptr == innerDict) if (nullptr == innerDict )
{
delete doc;
return false;
}
rootEle->LinkEndChild(innerDict);
bool ret = tinyxml2::XML_SUCCESS == doc->SaveFile(getSuitableFOpen(fullPath).c_str());
delete doc;
return ret;
}
bool FileUtils::writeValueVectorToFile(ValueVector vecData, const std::string& fullPath)
{
tinyxml2::XMLDocument *doc = new (std::nothrow)tinyxml2::XMLDocument();
if (nullptr == doc)
return false;
tinyxml2::XMLDeclaration *declaration = doc->NewDeclaration("xml version=\"1.0\" encoding=\"UTF-8\"");
if (nullptr == declaration)
{
delete doc;
return false;
}
doc->LinkEndChild(declaration);
tinyxml2::XMLElement *docType = doc->NewElement("!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\"");
doc->LinkEndChild(docType);
tinyxml2::XMLElement *rootEle = doc->NewElement("plist");
rootEle->SetAttribute("version", "1.0");
if (nullptr == rootEle)
{
delete doc;
return false;
}
doc->LinkEndChild(rootEle);
tinyxml2::XMLElement *innerDict = generateElementForArray(vecData, doc);
if (nullptr == innerDict)
{ {
delete doc; delete doc;
return false; return false;
@ -487,8 +443,8 @@ static tinyxml2::XMLElement* generateElementForObject(const Value& value, tinyxm
//object is bool //object is bool
if (value.getType() == Value::Type::BOOLEAN) { if (value.getType() == Value::Type::BOOLEAN) {
tinyxml2::XMLElement* node = doc->NewElement(value.asString().c_str()); tinyxml2::XMLElement* node = doc->NewElement(value.asString().c_str());
return node; return node;
} }
// object is Array // object is Array
@ -574,38 +530,7 @@ FileUtils::~FileUtils()
{ {
} }
bool FileUtils::writeStringToFile(std::string dataStr, const std::string& fullPath)
{
Data retData;
retData.copy((unsigned char*)dataStr.c_str(), dataStr.size());
return writeDataToFile(retData, fullPath);
}
bool FileUtils::writeDataToFile(Data retData, const std::string& fullPath)
{
size_t size = 0;
const char* mode = "wb";
CCASSERT(!fullPath.empty() && retData.getSize() != 0, "Invalid parameters.");
auto fileutils = FileUtils::getInstance();
do
{
// Read the file from hardware
FILE *fp = fopen(fileutils->getSuitableFOpen(fullPath).c_str(), mode);
CC_BREAK_IF(!fp);
size = retData.getSize();
fwrite(retData.getBytes(), size, 1, fp);
fclose(fp);
return true;
} while (0);
return false;
}
bool FileUtils::init() bool FileUtils::init()
{ {
@ -683,7 +608,7 @@ std::string FileUtils::getStringFromFile(const std::string& filename)
{ {
Data data = getData(filename, true); Data data = getData(filename, true);
if (data.isNull()) if (data.isNull())
return ""; return "";
std::string ret((const char*)data.getBytes()); std::string ret((const char*)data.getBytes());
return ret; return ret;
@ -831,7 +756,7 @@ std::string FileUtils::fullPathForFilename(const std::string &filename) const
// Get the new file name. // Get the new file name.
const std::string newFilename( getNewFilename(filename) ); const std::string newFilename( getNewFilename(filename) );
std::string fullpath; std::string fullpath;
for (const auto& searchIt : _searchPathArray) for (const auto& searchIt : _searchPathArray)
{ {
@ -967,16 +892,6 @@ void FileUtils::addSearchPath(const std::string &searchpath,const bool front)
{ {
path += "/"; path += "/";
} }
auto iter = std::find(_searchPathArray.begin(), _searchPathArray.end(), searchpath);
if (iter != _searchPathArray.cend())
{
if (front)
_searchPathArray.erase(iter);
else
return;
}
if (front) { if (front) {
_searchPathArray.insert(_searchPathArray.begin(), path); _searchPathArray.insert(_searchPathArray.begin(), path);
} else { } else {
@ -1026,6 +941,23 @@ std::string FileUtils::getFullPathForDirectoryAndFilename(const std::string& dir
return ret; return ret;
} }
std::string FileUtils::searchFullPathForFilename(const std::string& filename) const
{
if (isAbsolutePath(filename))
{
return filename;
}
std::string path = fullPathForFilename(filename);
if (0 == path.compare(filename))
{
return "";
}
else
{
return path;
}
}
bool FileUtils::isFileExist(const std::string& filename) const bool FileUtils::isFileExist(const std::string& filename) const
{ {
if (isAbsolutePath(filename)) if (isAbsolutePath(filename))
@ -1034,7 +966,7 @@ bool FileUtils::isFileExist(const std::string& filename) const
} }
else else
{ {
std::string fullpath = fullPathForFilename(filename); std::string fullpath = searchFullPathForFilename(filename);
if (fullpath.empty()) if (fullpath.empty())
return false; return false;
else else
@ -1047,6 +979,29 @@ bool FileUtils::isAbsolutePath(const std::string& path) const
return (path[0] == '/'); return (path[0] == '/');
} }
bool FileUtils::isDirectoryExistInternal(const std::string& dirPath) const
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
WIN32_FILE_ATTRIBUTE_DATA wfad;
std::wstring wdirPath(dirPath.begin(), dirPath.end());
if (GetFileAttributesEx(wdirPath.c_str(), GetFileExInfoStandard, &wfad))
{
return true;
}
return false;
#elif (CC_TARGET_PLATFORM != CC_PLATFORM_WIN32)
struct stat st;
if (stat(dirPath.c_str(), &st) == 0)
{
return S_ISDIR(st.st_mode);
}
return false;
#else
CCASSERT(false, "FileUtils not support isDirectoryExistInternal");
return false;
#endif
}
bool FileUtils::isDirectoryExist(const std::string& dirPath) const bool FileUtils::isDirectoryExist(const std::string& dirPath) const
{ {
CCASSERT(!dirPath.empty(), "Invalid path"); CCASSERT(!dirPath.empty(), "Invalid path");
@ -1063,7 +1018,7 @@ bool FileUtils::isDirectoryExist(const std::string& dirPath) const
return isDirectoryExistInternal(cacheIter->second); return isDirectoryExistInternal(cacheIter->second);
} }
std::string fullpath; std::string fullpath;
for (const auto& searchIt : _searchPathArray) for (const auto& searchIt : _searchPathArray)
{ {
for (const auto& resolutionIt : _searchResolutionsOrderArray) for (const auto& resolutionIt : _searchResolutionsOrderArray)
@ -1077,6 +1032,7 @@ bool FileUtils::isDirectoryExist(const std::string& dirPath) const
} }
} }
} }
return false; return false;
} }
@ -1115,45 +1071,27 @@ bool FileUtils::createDirectory(const std::string& path)
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) #if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
WIN32_FILE_ATTRIBUTE_DATA wfad; WIN32_FILE_ATTRIBUTE_DATA wfad;
std::wstring wpath(path.begin(), path.end()); std::wstring wpath(path.begin(), path.end());
if (!(GetFileAttributesEx(wpath.c_str(), GetFileExInfoStandard, &wfad))) if (!(GetFileAttributesEx(wpath.c_str(), GetFileExInfoStandard, &wfad)))
{ {
subpath = ""; subpath = "";
for(unsigned int i = 0 ; i < dirs.size() ; ++i) for(unsigned int i = 0 ; i < dirs.size() ; ++i)
{ {
subpath += dirs[i]; subpath += dirs[i];
if (i > 0 && !isDirectoryExist(subpath)) if (i > 0 && !isDirectoryExist(subpath))
{ {
std::wstring wsubpath(subpath.begin(), subpath.end()); std::wstring wsubpath(subpath.begin(), subpath.end());
BOOL ret = CreateDirectory(wsubpath.c_str(), NULL); BOOL ret = CreateDirectory(wsubpath.c_str(), NULL);
if (!ret && ERROR_ALREADY_EXISTS != GetLastError()) if (!ret && ERROR_ALREADY_EXISTS != GetLastError())
{ {
return false; return false;
} }
} }
} }
} }
return true; return true;
#elif (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) #elif (CC_TARGET_PLATFORM != CC_PLATFORM_WIN32)
if ((GetFileAttributesA(path.c_str())) == INVALID_FILE_ATTRIBUTES)
{
subpath = "";
for (unsigned 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; DIR *dir = NULL;
// Create path recursively // Create path recursively
@ -1182,6 +1120,9 @@ bool FileUtils::createDirectory(const std::string& path)
} }
} }
return true; return true;
#else
CCASSERT(false, "FileUtils not support createDirectory");
return false;
#endif #endif
} }
@ -1211,53 +1152,44 @@ bool FileUtils::removeDirectory(const std::string& path)
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) #if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
std::wstring wpath = std::wstring(path.begin(), path.end()); std::wstring wpath = std::wstring(path.begin(), path.end());
std::wstring files = wpath + L"*.*"; std::wstring files = wpath + L"*.*";
WIN32_FIND_DATA wfd; WIN32_FIND_DATA wfd;
HANDLE search = FindFirstFileEx(files.c_str(), FindExInfoStandard, &wfd, FindExSearchNameMatch, NULL, 0); HANDLE search = FindFirstFileEx(files.c_str(), FindExInfoStandard, &wfd, FindExSearchNameMatch, NULL, 0);
bool ret=true; bool ret=true;
if (search!=INVALID_HANDLE_VALUE) if (search!=INVALID_HANDLE_VALUE)
{ {
BOOL find=true; BOOL find=true;
while (find) while (find)
{ {
//. .. //. ..
if(wfd.cFileName[0]!='.') if(wfd.cFileName[0]!='.')
{ {
std::wstring temp = wpath + wfd.cFileName; std::wstring temp = wpath + wfd.cFileName;
if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{ {
temp += '/'; temp += '/';
ret = ret && this->removeDirectory(std::string(temp.begin(), temp.end())); ret = ret && this->removeDirectory(std::string(temp.begin(), temp.end()));
} }
else else
{ {
SetFileAttributes(temp.c_str(), FILE_ATTRIBUTE_NORMAL); SetFileAttributes(temp.c_str(), FILE_ATTRIBUTE_NORMAL);
ret = ret && DeleteFile(temp.c_str()); ret = ret && DeleteFile(temp.c_str());
} }
} }
find = FindNextFile(search, &wfd); find = FindNextFile(search, &wfd);
} }
FindClose(search); FindClose(search);
} }
if (ret && RemoveDirectory(wpath.c_str())) if (ret && RemoveDirectory(wpath.c_str()))
{ {
return true; return true;
} }
return false; return false;
#elif (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
std::string command = "cmd /c rd /s /q ";
// Path may include space.
command += "\"" + path + "\"";
if (WinExec(command.c_str(), SW_HIDE) > 31)
return true;
else
return false;
#elif (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) #elif (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC)
if (nftw(path.c_str(),unlink_cb, 64, FTW_DEPTH | FTW_PHYS)) if (nftw(path.c_str(),unlink_cb, 64, FTW_DEPTH | FTW_PHYS))
return false; return false;
else else
return true; return true;
#else #elif (CC_TARGET_PLATFORM != CC_PLATFORM_WIN32)
std::string command = "rm -r "; std::string command = "rm -r ";
// Path may include space. // Path may include space.
command += "\"" + path + "\""; command += "\"" + path + "\"";
@ -1265,6 +1197,9 @@ bool FileUtils::removeDirectory(const std::string& path)
return true; return true;
else else
return false; return false;
#else
CCASSERT(false, "FileUtils not support removeDirectory");
return false;
#endif #endif
} }
@ -1275,33 +1210,19 @@ bool FileUtils::removeFile(const std::string &path)
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) #if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
std::wstring wpath(path.begin(), path.end()); std::wstring wpath(path.begin(), path.end());
if (DeleteFile(wpath.c_str())) if (DeleteFile(wpath.c_str()))
{ {
return true; return true;
} }
return false; return false;
#elif (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) #elif (CC_TARGET_PLATFORM != CC_PLATFORM_WIN32)
std::string command = "cmd /c del /q ";
std::string win32path = path;
int len = win32path.length();
for (int i = 0; i < len; ++i)
{
if (win32path[i] == '/')
{
win32path[i] = '\\';
}
}
command += win32path;
if (WinExec(command.c_str(), SW_HIDE) > 31)
return true;
else
return false;
#else
if (remove(path.c_str())) { if (remove(path.c_str())) {
return false; return false;
} else { } else {
return true; return true;
} }
#else
CCASSERT(false, "FileUtils not support removeFile");
return false;
#endif #endif
} }
@ -1323,29 +1244,7 @@ bool FileUtils::renameFile(const std::string &path, const std::string &oldname,
return true; return true;
} }
return false; return false;
#elif (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) #elif (CC_TARGET_PLATFORM != CC_PLATFORM_WIN32)
std::regex pat("\\/");
std::string _old = std::regex_replace(oldPath, pat, "\\");
std::string _new = std::regex_replace(newPath, pat, "\\");
if(FileUtils::getInstance()->isFileExist(_new))
{
if (!DeleteFileA(_new.c_str()))
{
CCLOGERROR("Fail to delete file %s !Error code is 0x%x", newPath.c_str(), GetLastError());
}
}
if (MoveFileA(_old.c_str(), _new.c_str()))
{
return true;
}
else
{
CCLOGERROR("Fail to rename file %s to %s !Error code is 0x%x", oldPath.c_str(), newPath.c_str(), GetLastError());
return false;
}
#else
int errorCode = rename(oldPath.c_str(), newPath.c_str()); int errorCode = rename(oldPath.c_str(), newPath.c_str());
if (0 != errorCode) if (0 != errorCode)
@ -1354,6 +1253,9 @@ bool FileUtils::renameFile(const std::string &path, const std::string &oldname,
return false; return false;
} }
return true; return true;
#else
CCASSERT(false, "FileUtils not support renameFile");
return false;
#endif #endif
} }
@ -1364,7 +1266,7 @@ long FileUtils::getFileSize(const std::string &filepath)
std::string fullpath = filepath; std::string fullpath = filepath;
if (!isAbsolutePath(filepath)) if (!isAbsolutePath(filepath))
{ {
fullpath = fullPathForFilename(filepath); fullpath = searchFullPathForFilename(filepath);
if (fullpath.empty()) if (fullpath.empty())
return 0; return 0;
} }
@ -1460,7 +1362,6 @@ std::string FileUtils::getSuitableFOpen(const std::string& filenameUtf8) const
{ {
return filenameUtf8; return filenameUtf8;
} }
#endif #endif
NS_CC_END NS_CC_END

View File

@ -30,6 +30,7 @@ THE SOFTWARE.
#include "platform/CCCommon.h" #include "platform/CCCommon.h"
#include <Shlobj.h> #include <Shlobj.h>
#include <cstdlib> #include <cstdlib>
#include <regex>
using namespace std; using namespace std;
@ -56,6 +57,55 @@ static inline std::string convertPathFormatToUnixStyle(const std::string& path)
return ret; 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 void _checkPath() static void _checkPath()
{ {
if (0 == s_resourcePath.length()) if (0 == s_resourcePath.length())
@ -99,6 +149,17 @@ bool FileUtilsWin32::init()
return FileUtils::init(); return FileUtils::init();
} }
bool FileUtilsWin32::isDirectoryExistInternal(const std::string& dirPath) const
{
unsigned long fAttrib = GetFileAttributes(StringUtf8ToWideChar(dirPath).c_str());
if (fAttrib != INVALID_FILE_ATTRIBUTES &&
(fAttrib & FILE_ATTRIBUTE_DIRECTORY))
{
return true;
}
return false;
}
bool FileUtilsWin32::isFileExistInternal(const std::string& strFilePath) const bool FileUtilsWin32::isFileExistInternal(const std::string& strFilePath) const
{ {
if (0 == strFilePath.length()) if (0 == strFilePath.length())
@ -112,10 +173,7 @@ bool FileUtilsWin32::isFileExistInternal(const std::string& strFilePath) const
strPath.insert(0, _defaultResRootPath); strPath.insert(0, _defaultResRootPath);
} }
WCHAR utf16Buf[CC_MAX_PATH] = {0}; DWORD attr = GetFileAttributesW(StringUtf8ToWideChar(strPath).c_str());
MultiByteToWideChar(CP_UTF8, 0, strPath.c_str(), -1, utf16Buf, sizeof(utf16Buf)/sizeof(utf16Buf[0]));
DWORD attr = GetFileAttributesW(utf16Buf);
if(attr == INVALID_FILE_ATTRIBUTES || (attr & FILE_ATTRIBUTE_DIRECTORY)) if(attr == INVALID_FILE_ATTRIBUTES || (attr & FILE_ATTRIBUTE_DIRECTORY))
return false; // not a file return false; // not a file
return true; return true;
@ -206,10 +264,7 @@ static Data getData(const std::string& filename, bool forString)
// check if the filename uses correct case characters // check if the filename uses correct case characters
CC_BREAK_IF(!checkFileName(fullPath, filename)); CC_BREAK_IF(!checkFileName(fullPath, filename));
WCHAR wszBuf[CC_MAX_PATH] = {0}; HANDLE fileHandle = ::CreateFile(StringUtf8ToWideChar(fullPath).c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, nullptr);
MultiByteToWideChar(CP_UTF8, 0, fullPath.c_str(), -1, wszBuf, sizeof(wszBuf)/sizeof(wszBuf[0]));
HANDLE fileHandle = ::CreateFileW(wszBuf, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, nullptr);
CC_BREAK_IF(fileHandle == INVALID_HANDLE_VALUE); CC_BREAK_IF(fileHandle == INVALID_HANDLE_VALUE);
size = ::GetFileSize(fileHandle, nullptr); size = ::GetFileSize(fileHandle, nullptr);
@ -291,10 +346,7 @@ unsigned char* FileUtilsWin32::getFileData(const std::string& filename, const ch
// check if the filename uses correct case characters // check if the filename uses correct case characters
CC_BREAK_IF(!checkFileName(fullPath, filename)); CC_BREAK_IF(!checkFileName(fullPath, filename));
WCHAR wszBuf[CC_MAX_PATH] = {0}; HANDLE fileHandle = ::CreateFile(StringUtf8ToWideChar(fullPath).c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, nullptr);
MultiByteToWideChar(CP_UTF8, 0, fullPath.c_str(), -1, wszBuf, sizeof(wszBuf)/sizeof(wszBuf[0]));
HANDLE fileHandle = ::CreateFileW(wszBuf, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, nullptr);
CC_BREAK_IF(fileHandle == INVALID_HANDLE_VALUE); CC_BREAK_IF(fileHandle == INVALID_HANDLE_VALUE);
*size = ::GetFileSize(fileHandle, nullptr); *size = ::GetFileSize(fileHandle, nullptr);
@ -351,49 +403,191 @@ string FileUtilsWin32::getWritablePath() const
} }
// Get full path of executable, e.g. c:\Program Files (x86)\My Game Folder\MyGame.exe // Get full path of executable, e.g. c:\Program Files (x86)\My Game Folder\MyGame.exe
char full_path[CC_MAX_PATH + 1]; WCHAR full_path[CC_MAX_PATH + 1] = { 0 };
::GetModuleFileNameA(nullptr, full_path, CC_MAX_PATH + 1); ::GetModuleFileName(nullptr, full_path, CC_MAX_PATH + 1);
// Debug app uses executable directory; Non-debug app uses local app data directory // Debug app uses executable directory; Non-debug app uses local app data directory
//#ifndef _DEBUG //#ifndef _DEBUG
// Get filename of executable only, e.g. MyGame.exe // Get filename of executable only, e.g. MyGame.exe
char *base_name = strrchr(full_path, '\\'); WCHAR *base_name = wcsrchr(full_path, '\\');
wstring retPath;
if(base_name)
{
WCHAR app_data_path[CC_MAX_PATH + 1];
if(base_name) // Get local app data directory, e.g. C:\Documents and Settings\username\Local Settings\Application Data
if (SUCCEEDED(SHGetFolderPath(nullptr, CSIDL_LOCAL_APPDATA, nullptr, SHGFP_TYPE_CURRENT, app_data_path)))
{ {
char app_data_path[CC_MAX_PATH + 1]; wstring ret(app_data_path);
// Get local app data directory, e.g. C:\Documents and Settings\username\Local Settings\Application Data // Adding executable filename, e.g. C:\Documents and Settings\username\Local Settings\Application Data\MyGame.exe
if (SUCCEEDED(SHGetFolderPathA(nullptr, CSIDL_LOCAL_APPDATA, nullptr, SHGFP_TYPE_CURRENT, app_data_path))) ret += base_name;
// Remove ".exe" extension, e.g. C:\Documents and Settings\username\Local Settings\Application Data\MyGame
ret = ret.substr(0, ret.rfind(L"."));
ret += L"\\";
// Create directory
if (SUCCEEDED(SHCreateDirectoryEx(nullptr, ret.c_str(), nullptr)))
{ {
string ret((char*)app_data_path); retPath = ret;
}
}
}
if (retPath.empty())
//#endif // not defined _DEBUG
{
// If fetching of local app data directory fails, use the executable one
retPath = full_path;
// Adding executable filename, e.g. C:\Documents and Settings\username\Local Settings\Application Data\MyGame.exe // remove xxx.exe
ret += base_name; retPath = retPath.substr(0, retPath.rfind(L"\\") + 1);
}
// Remove ".exe" extension, e.g. C:\Documents and Settings\username\Local Settings\Application Data\MyGame return convertPathFormatToUnixStyle(StringWideCharToUtf8(retPath));
ret = ret.substr(0, ret.rfind(".")); }
ret += "\\"; bool FileUtilsWin32::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;
// Create directory std::regex pat("\\/");
if (SUCCEEDED(SHCreateDirectoryExA(nullptr, ret.c_str(), nullptr))) std::string _old = std::regex_replace(oldPath, pat, "\\");
std::string _new = std::regex_replace(newPath, pat, "\\");
std::wstring _wNew = StringUtf8ToWideChar(_new);
if (FileUtils::getInstance()->isFileExist(_new))
{
if (!DeleteFile(_wNew.c_str()))
{
CCLOGERROR("Fail to delete file %s !Error code is 0x%x", newPath.c_str(), GetLastError());
}
}
if (MoveFile(StringUtf8ToWideChar(_old).c_str(), _wNew.c_str()))
{
return true;
}
else
{
CCLOGERROR("Fail to rename file %s to %s !Error code is 0x%x", oldPath.c_str(), newPath.c_str(), GetLastError());
return false;
}
}
bool FileUtilsWin32::createDirectory(const std::string& dirPath)
{
CCASSERT(!dirPath.empty(), "Invalid path");
if (isDirectoryExist(dirPath))
return true;
std::wstring path = StringUtf8ToWideChar(dirPath);
// Split the path
size_t start = 0;
size_t found = path.find_first_of(L"/\\", start);
std::wstring subpath;
std::vector<std::wstring> dirs;
if (found != std::wstring::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(L"/\\", start);
if (found == std::wstring::npos)
{
if (start < path.length())
{ {
return convertPathFormatToUnixStyle(ret); dirs.push_back(path.substr(start));
}
break;
}
}
}
if ((GetFileAttributes(path.c_str())) == INVALID_FILE_ATTRIBUTES)
{
subpath = L"";
for (unsigned int i = 0; i < dirs.size(); ++i)
{
subpath += dirs[i];
std::string utf8Path = StringWideCharToUtf8(subpath);
if (!isDirectoryExist(utf8Path))
{
BOOL ret = CreateDirectory(subpath.c_str(), NULL);
if (!ret && ERROR_ALREADY_EXISTS != GetLastError())
{
CCLOGERROR("Fail create directory %s !Error code is 0x%x", utf8Path.c_str(), GetLastError());
return false;
} }
} }
} }
//#endif // not defined _DEBUG }
return true;
}
// If fetching of local app data directory fails, use the executable one bool FileUtilsWin32::removeFile(const std::string &filepath)
string ret((char*)full_path); {
std::regex pat("\\/");
std::string win32path = std::regex_replace(filepath, pat, "\\");
// remove xxx.exe if (DeleteFile(StringUtf8ToWideChar(win32path).c_str()))
ret = ret.substr(0, ret.rfind("\\") + 1); {
return true;
}
else
{
CCLOGERROR("Fail remove file %s !Error code is 0x%x", filepath.c_str(), GetLastError());
return false;
}
}
ret = convertPathFormatToUnixStyle(ret); bool FileUtilsWin32::removeDirectory(const std::string& dirPath)
{
return ret; std::wstring wpath = StringUtf8ToWideChar(dirPath);
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(StringWideCharToUtf8(temp));
}
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;
} }
NS_CC_END NS_CC_END

View File

@ -49,12 +49,53 @@ class CC_DLL FileUtilsWin32 : public FileUtils
public: public:
/* override funtions */ /* override funtions */
bool init(); bool init();
virtual std::string getWritablePath() const; virtual std::string getWritablePath() const override;
virtual bool isAbsolutePath(const std::string& strPath) const; virtual bool isAbsolutePath(const std::string& strPath) const override;
protected: protected:
virtual bool isFileExistInternal(const std::string& strFilePath) const override; 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; 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;
/** /**
* Gets resource file data * Gets resource file data
* *