无法使用 fstream 和 ifstream 在 NDK C++ 中读取文件
Failed to read files in NDK C++ using fstream and ifstream
我正在尝试使用 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 中提供了外部存储写入和读取权限,但没有帮助。
这个问题与格式无关,因为我试图在路径中放置不同的文件。为什么读取文件失败?
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".
您的应用需要 READ_EXTERNAL_STORAGE 权限。
这是一个有助于在运行时请求此权限的小片段:请参阅 。
我正在尝试使用 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 中提供了外部存储写入和读取权限,但没有帮助。 这个问题与格式无关,因为我试图在路径中放置不同的文件。为什么读取文件失败?
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".
您的应用需要 READ_EXTERNAL_STORAGE 权限。
这是一个有助于在运行时请求此权限的小片段:请参阅