简体   繁体   中英

Failed to read files in NDK C++ using fstream and ifstream

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM