仅在NDK中读取文件时出现问题,写入文件是没有错误的

时间:2015-11-04 14:48:59

标签: android file android-ndk

这个简单的写入程序在我的模拟器中正常运行,因为我在sdcard中生成一个文本文件(文本文件中包含HELLO WORLD)以及给定的消息模拟器屏幕。

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)!");
}

但是当我尝试使用此程序读取文件时,我遇到了问题。它在仿真器屏幕或logcat上不输出任何内容。从上面的程序可以看出,sdcard的位置或使用FILE操作肯定没有问题。如何解决?

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)!");

}

由于

修改

以上代码读取文件在linux gcc中运行良好,但在Android中有错误。如安德鲁所提到的那样改变它解决了它。

1 个答案:

答案 0 :(得分:1)

fgetc()返回int,而不是char,因此此循环永不终止:

    while((ch=fgetc(fptr))!=EOF)
        cnt++;

因为ch永远不能等于EOF