Issue
In order to write to a file on sdcard to add android.permission.WRITE_EXTERNAL_STORAGE in AndroidManifest.xml. What need to add / do to keep a record of the device memory (flash / application folder)?
Write function:
bool write_to_file(const std::string & file_name, const std::string & text)
{
bool res = false;
std::ofstream stream (file_name.c_str (), std::ios::out);
stream.clear();
if (! stream.fail()) {
res = true;
stream << text.c_str() << std::endl;
}
else {
LOGE ("std :: ofstream: wtire error");
}
stream.close();
return res;
}
Call example
std::string file("/sdcard/text.txt");
write_to_file(file, "simple text"); // OK !!!
std::string file("./text.txt");
write_to_file(file, "simple text"); // ERROR !!!
Solution
The trick is passing the right file name to the native code. In Android, you use Context.getDir()
to retrieve a data folder location in the phone memory. Like this:
File Path = Ctxt.getDir("Data");
File FName = new File(Path, "MyFile.txt");
Then pass FName.toString()
into the native library somehow. The pasted snippet won't be directly callable from Java - the glue code is missing.
In versions of Android that I know of, the file path above would correspond to the following filesystem path: /data/data/com.mypackage/app_Data/MyFile.txt
. But you cannot rely on that.
Writing to arbitrary paths of the device filesystem is prohibited by OS permissions. You have your sandbox, go play in it. Such is the smartphone way.
Answered By - Seva Alekseyev
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.