mercredi 4 novembre 2015

Problems only with reading a file in NDK, writing to a file is error free

This simple program to write into a file is running fine in my emulator as I am getting a text file generated inside the sdcard(text file has HELLO WORLD in it) along with the given message on emulator screen.

jstring
Java_com_example_hellojni_HelloJni_stringFromJNI( JNIEnv* env,
                                              jobject thiz )
{
    FILE* file = fopen("/sdcard/hello.txt","w+");

    if (file != NULL)
    {
        fputs("HELLO WORLD!\n", file);
        fflush(file);
        fclose(file);
    }

    return (*env)->NewStringUTF(env, "Hello from JNI (with file io)!");
}

But when I try to read the file using this program I am facing problems. It outputs nothing on the emulator screen or on logcat. As seen from the above program there definitely is no problem with the location of sdcard or with using FILE operations. How to fix it?

JNIEXPORT jstring JNICALL Java_com_example_myproject_MainActivity_doSomething( JNIEnv* env, jobject thiz)
{
        // Counts the characters inside file

        char ch;
        int cnt= 0;
        FILE* fptr = fopen("/sdcard/hello.txt","r");

        while((ch=fgetc(fptr))!=EOF)
            cnt++;
        fclose(fptr);
        LOGE("cnt: %d",cnt);

        return (*env)->NewStringUTF(env, "Hello from JNI (with file io)!");

}

Thanks

Aucun commentaire:

Enregistrer un commentaire