I am currently working on a C-based, NDK-based, Android application. This application needs to create temporary files. On a regular Linux system, I would use tmpfile
to ensure that these files are properly created in a temporary directory and cleaned-up at process end.
However, my investigations on various Android devices seem to indicate that
tmpfile
always fails;/tmp
directory;/data/local/tmp
isn't present on all variants of Android;TEMP
environment variable set;mkstemp
doesn't work any better than tmpfile
.Now, I'm sure that I could hack something together, but seeing that the SDK offers context.getCacheDir
and File.createTempFile
for Java applications, I hope that there is an equivalent at C-level.
Does anyone know of a good reliable and cross-Android method for creating a temporary file?
The best way we've found is to call Context.getCacheDir
on startup, get its path with getAbsolutePath
, then call a JNI function to store that path in a global. Any function that wants to create a temporary file simply appends a suitable temporary file name to that path.
If you really want to fetch it from JNI another alternative would be to pass in a Context
to a JNI function and use a bunch of GetMethodID
/ CallObjectMethod
stuff to call back into Java to getCacheDir
, but the former approach is a lot simpler.
Unfortunately, there does not appear to be a more elegant solution at the moment.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With