Search code examples
androidresourcesassetsifstreamandroid-ndk

Can I use ifstream in Android NDK to access Assets?


My question is pretty simple, but I am having a hard time finding any info about this online.

Is it possible to use ifstream to open a file from assets and/or resources using Android NDK?

For example, placing a test.txt file in /assets and trying the following does not work:

    char pLine[256];
    std::ifstream fin("/assets/test.txt");
    if(!fin.fail())
    {
        LOGD( "test.txt opened" );
        while( !fin.eof() )
        {
            fin.getline( pLine, 256 );
            LOGD(pLine);
        }
    }
    else
    {
        LOGD( "test.txt FAILED TO OPEN!" );
    }
    fin.close();

Nor does any variable of:

    std::ifstream fin("assets/test.txt");

    std::ifstream fin("test.txt");

Etc..., nor placing it in /res instead.

So, is it possible to use normal ifstream operators to access assets and or resource files?


Solution

  • No, you cannot. Assets are stored within the apk, a zip file. ifstream cannot read within the zip file.

    To access these files you either need to access them in java and save them elsewhere or extract the contents of the apk to get to the assets.

    Here is an example of doing the former.

    http://www.itwizard.ro/android-phone-installing-assets-how-to-60.html

    Here is an example of doing the latter.

    http://www.anddev.org/ndk_opengl_-_loading_resources_and_assets_from_native_code-t11978.html