3

I am trying to load a file in NDK using ifstream but it fails to read it. I've double checked the path of the file and it is not wrong. The same program works in normal C++(without the JNI stuff ofcourse).

#include <jni.h>
#include <string>
#include <iostream>
#include <istream>
#include <sstream>
#include <fstream> 
using namespace std;
extern "C"
{

JNIEXPORT jstring JNICALL Java_com_example_aaaaatrytest_MainActivity_stringFromJNI(JNIEnv *env, jobject /* this */) {
    string file_path = "/home/moe/Desktop/blah.txt";
    std::ifstream fim(file_path);
    if(fim.is_open())
    {
    string pass = "File Loaded";
    return env->NewStringUTF(pass.c_str());
    }
    else{
    std::string fail = "Failed to load file";
    return env->NewStringUTF(fail.c_str());
    }
}
}

After removing if-else and debugging, this is what debugger displays:

SIGTRAP (signal SIGTRAP)
env = {JNIEnv * | 0x55bc7ccc00} 0x00000055bc7ccc00
{jobject | 0x7fcefb1af4} 0x0000007fcefb1af4

I have tried to use fstream instead of ifstream but same error. I've also provided external storage write and read permission in manifest.xml but it didn't help. This problem is format independent as I've tried to put different files in the path. Why is it failing to read the file?

  • 1
    `"/home/moe/Desktop/blah.txt"` <-- That looks like a path that might exist on a computer, not like a path that would exist on an Android device. – Michael Feb 09 '19 at 11:18
  • @Michael, l have copied the file to my device and gave android path but it still fails to read. My android's path to file looks like this "/storage/emulated/0/abc/abc.txt" – UniverseGOD2525 Feb 09 '19 at 12:19
  • 2
    _"I've also provided external storage write and read permission in manifest.xml"_ Note that it isn't enough to just state in the manifest that your app might be using those permissions. You also have to request the permissions at runtime. At least if your app is targeting API level 23 or above. – Michael Feb 09 '19 at 22:56
  • @Michael, Thanks! I asked for permission in run-time and it works now! – UniverseGOD2525 Feb 11 '19 at 04:53

1 Answers1

4

l have copied the file to my device and gave android path but it still fails to read. My android's path to file looks like this "/storage/emulated/0/abc/abc.txt".

Your app needs READ_EXTERNAL_STORAGE permission.

Here is a small snippet that helps to request this permission at runtime: see READ_EXTERNAL_STORAGE permission is in manifest but still doesn't work.

Alex Cohn
  • 56,089
  • 9
  • 113
  • 307