【发布时间】:2019-02-11 15:40:53
【问题描述】:
我正在尝试使用 ifstream 在 NDK 中加载一个文件,但它无法读取它。我已经仔细检查了文件的路径,它没有错。相同的程序在普通 C++ 中工作(当然没有 JNI 的东西)。
#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());
}
}
}
删除 if-else 并调试后,调试器显示如下:
SIGTRAP (signal SIGTRAP)
env = {JNIEnv * | 0x55bc7ccc00} 0x00000055bc7ccc00
{jobject | 0x7fcefb1af4} 0x0000007fcefb1af4
我尝试使用 fstream 而不是 ifstream 但同样的错误。我还在 manifest.xml 中提供了外部存储写入和读取权限,但它没有帮助。 这个问题与格式无关,因为我试图将不同的文件放在路径中。为什么无法读取文件?
【问题讨论】:
-
"/home/moe/Desktop/blah.txt" -
@Michael,我已将文件复制到我的设备并提供了 android 路径,但仍然无法读取。我的 android 的文件路径看起来像这样“/storage/emulated/0/abc/abc.txt”
-
“我还在 manifest.xml 中提供了外部存储写入和读取权限” 请注意,仅在清单中说明您的应用可能是不够的使用这些权限。您还必须在运行时请求权限。至少如果您的应用面向 API 级别 23 或更高级别。
-
@Michael,谢谢!我在运行时请求了许可,它现在可以工作了!
标签: android c++ android-ndk