我通过使用开始工作CCFileUtils( )::sharedFileUtils( ) -> fullPathFromRelativePath( "POSDATA.GAMEDATA" );
更详细的解释:
- 通过转到左侧的项目树和
Right-click -> Add Files
. 我所做的是添加了一个与and文件夹Data
同级的新文件夹,并将我的文件放在那里。在 Xcode 中,我添加了一个新组并将该文件添加到该组中。Resources
Classes
POSDATA.GAMEDATA
- 然后我用来
ifstream
打开文件。
- 打开文件时,使用
CCFileUtils( )::sharedFileUtils( ) -> fullPathFromRelativePath( )
获取文件的绝对路径。fullPathFromRelativePath( )
在as 参数上提供文件名。
- 尝试运行它,它应该可以正常工作。
一个小例子:
// FileReader.h
#include "cocos2d.h"
using namespace std;
using namespace cocos2d;
class FileReader {
private:
vector< string > mFileContents;
public:
FileReader( string pFileName, char pMode = 'r' );
};
// FileReader.cpp
#include "FileReader.h"
#include <fstream>
#include "cocos2d.h"
using namespace cocos2d;
using namespace std;
FileReader::FileReader( string pFileName, char pMode ) {
// Create input file stream
ifstream inputStream;
string thisLine;
// Open file
inputStream.open( CCFileUtils( )::sharedFileUtils( ) -> fullPathFromRelativePath( pFileName ).c_str( ) );
// Check if it is open
if ( !inputStream.is_open( ) ) {
cerr << "[ ERROR ] Cannot open file: " << pFileName.c_str( ) << endl;
exit( 1 );
}
while ( getline( inputStream, thisLine ) ) {
// Put all lines in vector
mFileContents.push_back( thisLine );
}
inputStream.close( );
cout << "[ NOTICE ] Finished opening file: " << pFileName.c_str( ) << endl;
}
此类将加载具有名称的文件pFileName
并将其放在其成员变量mFileContents
中。(请注意,它应该具有访问的public get
功能,因为它是)vector< string > getFileContents( )
mFileContents
private
编辑:上面的示例适用于 iOS,但不适用于 Android 设备。所以要解决这个问题,而不是使用ifstream
,CCFileUtils::sharedUtils( ) -> getFileData( )
而是使用。结合CCFileUtils::sharedUtils( ) -> fullPathFromRelativePath( )
,我们将能够实现读取适用于 iOS 和 Android 的纯文本文件的目标。
然后FileReader
类将是这样的:
// FileReader.cpp
#include "FileReader.h"
#include <fstream>
#include "cocos2d.h"
using namespace cocos2d;
using namespace std;
FileReader::FileReader( string pFileName, char pMode ) {
// Initialize variables needed
unsigned long fileSize = 0;
unsigned char * fileContents = NULL;
string thisLine, result, fullPath, contents;
// Get absolute path of file
fullPath = CCFileUtils::sharedFileUtils( ) -> fullPathFromRelativePath( pFileName.c_str( ) );
// Get data of file
fileContents = CCFileUtils::sharedFileUtils( ) -> getFileData( fullPath.c_str( ) , "r", &fileSize );
contents.append( ( char * ) fileContents );
// Create a string stream so that we can use getline( ) on it
istringstream fileStringStream( contents );
// Get file contents line by line
while ( getline( fileStringStream, thisLine ) ) {
// Put all lines in vector
mFileContents.push_back( thisLine );
}
// After this, mFileContents will have an extra entry and will have the value '\x04'.
// We should remove this by popping it out the vector.
mFileContents.pop_back( );
// Delete buffer created by fileContents. This part is required.
if ( fileContents ) {
delete[ ] fileContents;
fileContents = NULL;
}
// For testing purposes
cout << "[ NOTICE ] Finished opening file: " << pFileName.c_str( ) << endl;
}