Friday, December 02, 2011

fopen with native library on Android

If you develop an Android application with some native C/C++ layer (NDK) and 
try to open the file from it by doing FILE *pFile = fopen ("myfile.txt" ,"w");
the fopen call will fail.

The reason is that the current working directory for you application is the root of file system '/' and naturally your application doesn't have access to it.

In order to fix this problem you have to pass the full path for the file to fopen call.
One way to do this is to pass the base path to your application data folder where your application has read/write permissions. For example you can use the Context API getFilesDir().getAbsolutePath()
and pass the result to the native function call.
This particular API resolves currently into something like: "/data/data/[app package]/files/"

In your native code then the fopen call should succeed with 
FILE *pFile = fopen ("/data/data/[app package]/files/myfile.txt" ,"w"); 

Hope this was helpful.

3 comments:

Anonymous said...

Thanks, this was really useful!

Anonymous said...

Thanks so much! It helped me a lot!

Anonymous said...

Thanks so much! It helped me.