How is it possible to access files which are generated from a DocumentFile in Android KitKat/Lollipop in Native JNI Code, so I can use fopen, fread, etc. I'm particular asking this to access the external SD-Card files via the NDK.
Asked
Active
Viewed 2,525 times
14
-
See: https://stackoverflow.com/a/59004193/3768831 – Rick Wildes Feb 12 '21 at 04:18
1 Answers
12
You can use file descriptors:
ParcelFileDescriptor filePfd;
DocumentFile file;
filePfd = getContentResolver().openFileDescriptor(file.getUri(), "w");
int fd = filePfd.getFd();
This int fd
can be passed to JNI and used as usual C++ file descriptor:
FILE* file = NULL;
file = fdopen(fd, "r+b");
And you need permission to access to file or directory on SD-card

Maxim Metelskiy
- 1,389
- 14
- 29
-
Do you need to do a fclose for the fdopen? or would this create a problem when closing the file descriptor? – PerracoLabs Aug 26 '18 at 17:05
-
@PerracoLabs File Pointer and File Descriptor are different entities. So, I think, you need to do fclose(). But the best way to find out is to test it. Also you can check: https://stackoverflow.com/questions/2423628/whats-the-difference-between-a-file-descriptor-and-file-pointer – Maxim Metelskiy Aug 28 '18 at 15:21
-
@PerracoLabs calling fclose would be a bad idea as it does an implied `close` and when the Java side gets control it will also do a `close` because `getFd()` does not transfer ownership. The Java code could call `detachFd()` instead then calling `fclose` on the native side would be okay. the only thing is if an error path prevents the native code from getting to the `fdopen` the `fd` needs to be freed still. The other option might be to do `fdopen(dup(fd), "r+b")` on the native side instead (note the call to `dup`) and then call `fclose` on the file pointer. – Rick Wildes Feb 12 '21 at 03:53