Yet another question about Android assets directory

I’m using: cocos2d-2.0-rc2-x-2.0.1, ubuntu

I am able to successfully build and run my Cocos2dx project on Android. However, when I run the game, it crashes because it is unable to open a file. The file it is looking for is called “first.ini”, and it is located on my hard drive in .ini

When I call build_native.sh, an folder is created that is linked to the folder.

Then in Eclipse, the folder appears in the Package Explorer window and I can see the full path: .ini

However, in my code, none of the following calls to fopen will work:

@
pFile = fopen( “ini/first.ini”, “r” );
pFile = fopen( “/ini/first.ini”, “r” );
pFile = fopen( “./ini/first.ini”, “r” );
pFile = fopen( “assets/ini/first.ini”, “r” );
pFile = fopen( “/assets/ini/first.ini”, “r” );
pFile = fopen( “./assets/ini/first.ini”, “r” );
pFile = fopen( “first.ini”, “r” );
@

I must be doing something dumb….can somebody point out the problem?

thanks in advance!

I had exactly same problem one month before :wink: . But its solved by using CCFileUtils instead of fopen, because fopen (according to my understanding) cannot read the data inside the assets folder since the assets folder will be compressed and wrapped inside the apk file.

CCFileUtils *fileUtils = CCFileUtils::sharedFileUtils();

// long value that holds the file size in bytes
unsigned long fileSize;
unsigned char *fileData = fileUtils->getFileData("first.ini", "rb", &fileSize);

fileData contains pointer to the byte data of the file.

Same way if you want to write data into file dont use hard coded paths. Use the CCFileUtils to get the writable path.

// fetching the writable path
std::string writablePath = fileUtils->getWriteablePath();

// char array to store the full path
char path[512];
sprintf(path, "%s%s", writablePath.c_str(), "first.ini");

pw = fopen(path,"wb");
if( pw && fileSize > 0 ){
    fwrite(fileData, 1, fileSize, pw);
}

Ah yes! That appears to be the problem and the solution. I’ve been pulling my hair out on this one. Thanks a ton for posting!

(…and now to rewrite all my FILE* based code to work with char*… :b)