cocos2dx 3.x fullPathForFilename及isFileExist在ios/mac下与win32下行为不同

时间:2023-02-06 22:19:17

一,fullPathForFilename

项目先开发了ios/mac版本,这两天想把win32工程也配好,但遇到了部分资源无法正确找到的问题。

进一步观察发现,对于那些找不到的资源路径,fullPathForFilename将传入的短路径直接原样返回,而不是返回全路径。

查看fullPathForFilename的实现代码,有这样一段:

// FIXME: Should it return nullptr ? or an empty string ?
// The file wasn't found, return the file name passed in.
return filename;

即当前的处理是如果路径找不到,就将参数原样返回。

因此初步确定是因为路径没找到造成的,那么为什么找不到呢?

在fullPathForFilename的实现内打断点,查看_searchPathArray的值,发现其中的路径是对的:

cocos2dx 3.x fullPathForFilename及isFileExist在ios/mac下与win32下行为不同

但其中fullpath = this->getPathForFilename(newFilename, resolutionIt, searchIt)一句返回的fullpath却是空。

于是跟到getPathForFilename中断点,发现在其中path = getFullPathForDirectoryAndFilename(path, file)一句之前构造的路径都是与预期相符的,而此句返回的path却是空字符串。

于是再跟到getFullPathForDirectoryAndFilename中,发现其中有下面代码:

// if the file doesn't exist, return an empty string
if (!isFileExistInternal(ret)) {
ret = "";
}

于是明白了,原来是ios/mac上的isFileExistInternal与win32上的isFileExistInternal行为不一致,在ios/mac上,isFileExistInternal无论传入文件路径还是文件夹路径,只要路径存在,都会返回true;而在win32平台上,isFileExistInternal只有传入的是文件路径且文件存在时才会返回true,而如果传入文件夹路径,则总会返回false。我在项目中使用了fullPathForFilename去获得文件夹的全路径,于是在ios/mac下能正常工作,但在win32上不能正常工作。

一个简单的方法是直接将getFullPathForDirectoryAndFilename中那段代码改成:

// if the file doesn't exist, return an empty string
if (!isFileExistInternal(ret)
&&!isDirectoryExistInternal(ret)//added [yang chao]
) {
ret = "";
}

这样win32上fullPathForFilename的行为就与ios/mac上相同了。

二,isFileExist

isFileExist中使用了isFileExistInternal函数,所以isFileExist的行为在win32上也与ios/mac上不一致。在ios/mac上,判断文件或文件夹是否存在都可以用isFileExist函数,而在win32平台上isFileExist只能判断文件是否存在,如果想判断文件夹是否存在,要用isDirectoryExist函数。