androidc++android-ndkassetsreadfile

Android c++ AAsset_read reads wrong data


I read content of text files from assets. However, if I read second file then I get wrong result. It is mixed with previous file.

Here is first file, this is correctly written to buffer by AAsset_read:

uniform   mat4 uMVPMatrix;

attribute vec4 vPosition;
attribute vec4 a_Color;

varying vec4 v_Color;

void main() 
{ 
   gl_Position = uMVPMatrix * vPosition;
   v_Color = a_Color;
}

Here is second file, this is how it really looks and is expected to be written to buffer:

precision mediump float; 

varying vec4 v_Color;
uniform float alpha;
 
void main() 
{ 
    gl_FragColor = v_Color;
    gl_FragColor.a = gl_FragColor.w * alpha;
}

However, this is what is written to buffer by AAsset_read. It adds "v_Color = a_Color;\n}"" at the end, this is part of content from first file.

"precision mediump float; \n\nvarying vec4 v_Color;\nuniform float alpha;\n \nvoid main() \n{ \n    gl_FragColor = v_Color;\n    gl_FragColor.a = gl_FragColor.w * alpha;\n}v_Color = a_Color;\n}"

Here is method what I use:

std::string Assets::getTextFile(const char *file) {
        AAsset *asset = AAssetManager_open(android_assetManager, file, AASSET_MODE_UNKNOWN);

        int size = AAsset_getLength(asset);       
        char *bits = new char[size];

        AAsset_read(asset, bits, size);
        AAsset_close(asset);

        std::string a(bits);

        return a;
}

I am on android 13 and ndk is 24.0.8215888

Any idea what I do wrong?


Solution

  • AAsset_read's job is to read bytes from an asset, it does NOT add a terminating NUL byte. You should tell the std::string constructor the exact size:

    std::string a(bits, size);
    

    You also forgot to free bits again. You can improve the code by having AAsset_read put its data directly into your string and skipping the extra copy.

    std::string ret(size, 0);
    AAsset_read(asset, ret.data(), size);