To access the /sdcard/ path in C++ native code on Android, you have several options:
Option 1: Pass the path from Java to C++
The most straightforward approach is to get the path in Java and pass it to your native code:
Java side:
String externalStoragePath = Environment.getExternalStorageDirectory().getPath();
// Pass to native method
nativeMethod(externalStoragePath);
C++ side:
extern "C" JNIEXPORT void JNICALL
Java_com_example_app_MainActivity_nativeMethod(JNIEnv* env, jobject /* this */, jstring path) {
const char* nativePath = env->GetStringUTFChars(path, nullptr);
// Use the path
std::string storagePath(nativePath);
env->ReleaseStringUTFChars(path, nativePath);
}
Option 2: Call Java method from C++
You can call the Java Environment.getExternalStorageDirectory() method directly from C++:
std::string getExternalStoragePath(JNIEnv* env) {
// Get Environment class
jclass envClass = env->FindClass("android/os/Environment");
// Get the getExternalStorageDirectory method ID
jmethodID getExtStorageMethod = env->GetStaticMethodID(
envClass,
"getExternalStorageDirectory",
"()Ljava/io/File;"
);
// Call getExternalStorageDirectory()
jobject fileObject = env->CallStaticObjectMethod(envClass, getExtStorageMethod);
// Get File class and getPath method
jclass fileClass = env->GetObjectClass(fileObject);
jmethodID getPathMethod = env->GetMethodID(fileClass, "getPath", "()Ljava/lang/String;");
// Call getPath()
jstring pathString = (jstring)env->CallObjectMethod(fileObject, getPathMethod);
// Convert to C++ string
const char* path = env->GetStringUTFChars(pathString, nullptr);
std::string result(path);
env->ReleaseStringUTFChars(pathString, path);
// Clean up local references
env->DeleteLocalRef(envClass);
env->DeleteLocalRef(fileObject);
env->DeleteLocalRef(fileClass);
env->DeleteLocalRef(pathString);
return result;
}
Option 3: Use hardcoded path (not recommended)
While /sdcard/ often works, it's not guaranteed across all devices:
const char* externalStoragePath = "/sdcard/";
// Or more commonly:
const char* externalStoragePath = "/storage/emulated/0/";
Important Notes:
-
Permissions: Make sure you have the necessary permissions in your AndroidManifest.xml:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
-
Scoped Storage: Starting from Android 10 (API 29), access to external storage is restricted. You might need to use scoped storage APIs or request legacy storage access.
-
Runtime Permissions: For Android 6.0+ (API 23+), you need to request storage permissions at runtime.
The first two options are preferred as they use the proper Android APIs to get the correct path for the specific device.