Reading a file with ndk on Android 14

275 views
Skip to first unread message

Andrea Fiorito

unread,
Jan 16, 2024, 11:15:09 AMJan 16
to android-ndk
the question sounds quite trivial, but I couldn't find an answer.

I'm porting a computer vision library to android from linux and it requires a settings file (.yaml) and a big (100mb) vocabulary file (.txt). I thought to create a folder on /sdcard/ and copy those files there. the library uses cv::FileStorage to read the file, from OpenCV. It fails with the message on logs (cerr) : " global persistence.cpp:512 open Can't open file: '/sdcard/MyFolder/Settings.yaml' in read mode".

I tried from a new C++ project, to read the file myself with the snippet:

    std::string hello = "Hello from C++"; // from basic c++ project template
    //ifstream in("/storage/self/primary/MyFolder/Settings.yaml");
    ifstream in("/sdcard/MyFolder/Settings.yaml");
    LOGI("File is %s", in.good() ? "good" : "bad");
    for (int i = 0; i < 10; i++)
    {
        string text;
        getline(in, text);
        LOGI("%s", text.c_str());
    }
    return env->NewStringUTF(hello.c_str());

but no luck. On Log i get "file is bad" and then 10 empty lines.
I tried various combinations of permissions READ_EXTERNAL_STORAGE, READ_MEDIA_AUDIO, READ_MEDIA_IMAGES, READ_MEDIA_VIDEO and to ask permissions at runtime after migrating to AndroidX. 
I actually have no idea if I can even use the filesystem at this point.

Where can I store a configuration file so an user (of the prototype) can upload their settings and the lib can read it through OpenCV FileStorage and what other steps are necessary? (Permissions, etc.)

Probably related: https://stackoverflow.com/questions/75934748/read-write-file-with-ndk-always-gives-me-errno-13-permission-denied



Andrea Fiorito

unread,
Jan 16, 2024, 5:13:15 PMJan 16
to android-ndk
In the end, the solution for my use case was to use the folder from kotlin with getExternalFilesDir and pass it to a jni function configDirPath this way:
getExternalFilesDir(null)?.absolutePath?.let { configDirPath(it) }

Funny thing was that after creating the folders with mkdirs() in kotlin, the file (directory) 'com.sample.textureview' existed the (File method exists() returned true) but it was not visible on the file manager on Android studio, nor was visible with adb shell and ls, although with adb shell the directory was accessible and I could see the 'files' directory inside it. It was like the directory had the x permission set but not the r one as linux permissions.

Looked like that folder doesn't need any 'android permissions' and an user can adb push files into it.

Would be cool to have a sample that details other similar directories, and maybe common paths where I would expect to read/write but it's impossible to do that, as /sdcard. 
Reply all
Reply to author
Forward
0 new messages