10

I need to read text file from asset folder in android, by searching through internet I found that there is asset_manager api available from android 2.3 onwards. As I am targeting only tablet devices this is useful. But as I am not expert in C language I am not able to find any example on how to read/write files using file descriptor. I found many examples using FILE* (file pointers)

My goal is to decrypt a js file from asset folder which is encrypted using C (for securing the code), as js code is visible if end user decompiled my apk. Because asset folder is inside zip file is it possible to do?

Sandeep Manne
  • 6,030
  • 5
  • 39
  • 55

3 Answers3

35

Here is the code I used to read file from android assets folder using asset_manager ndk lib

    AAssetManager* mgr = AAssetManager_fromJava(env, assetManager);
    AAsset* asset = AAssetManager_open(mgr, (const char *) js, AASSET_MODE_UNKNOWN);
    if (NULL == asset) {
        __android_log_print(ANDROID_LOG_ERROR, NF_LOG_TAG, "_ASSET_NOT_FOUND_");
        return JNI_FALSE;
    }
    long size = AAsset_getLength(asset);
    char* buffer = (char*) malloc (sizeof(char)*size);
    AAsset_read (asset,buffer,size);
    __android_log_print(ANDROID_LOG_ERROR, NF_LOG_TAG, buffer);
    AAsset_close(asset);

Added following line to my Android.mk

# for native asset manager
LOCAL_LDLIBS    += -landroid

And don't forget the include in source file

#include <android/asset_manager.h>
Mirsaes
  • 43
  • 2
Sandeep Manne
  • 6,030
  • 5
  • 39
  • 55
2

Practically FILE* and 'int' descriptors are equivalent and fread/fwrite/fopen/fclose are the counterparts of open/close/read/write functions (the functions are not equivalent however, the latter are non-blocking).

To get 'int' from 'FILE*' you can use

int fileno(FILE* f);

in header and to do the inverse you can use fdopen()

FILE *fdopen(int fd, const char *mode);

So either replace everything using the FILE* to int or just take one of the samples and insert this conversion code before the file reading.

Viktor Latypov
  • 14,289
  • 3
  • 40
  • 55
  • 1
    OK. That has nothing to do with NDK actually, so if you post some C code here that you're having trouble with, the community will be able to help you better. Good luck with the coding :) – Viktor Latypov May 02 '12 at 07:33
2

It's pretty similar to regular fread/fseek functions. Here's read function declaraton:

ssize_t read(int fd, void *buf, size_t count);

It reads from fd file descriptor into buf buffer count bytes. If you think about fread, then instead of:

fread(buf, count, size, file);

you will call:

read(fd, buf, count*size);

And that's it. It is so simple.

Seeking is also similar. Just look up the function declaration and read the argument names/description. It will be obvious.

Mārtiņš Možeiko
  • 12,733
  • 2
  • 45
  • 45