在安卓模拟器中无法写入文件

4

问题描述

我正在编写一个Android应用程序并使用本地代码,在Android模拟器上进行测试。为了查看JNI代码中发生的情况,我在Android /data/LogTest/文件夹中创建文件,并在其中写入我的日志信息。

FILE * pFile;
pFile = fopen ("/data/LogTest/Log.txt"", "w");
// .... 
// Write some logs to file ...
// ....

当我第一次运行Android应用程序时,一切都很顺利,我可以在Log.txt文件中看到日志。但是当我关闭Android应用程序并再次运行它时,什么也没有发生。就像应用程序第二次无法将日志写入文件。
自我想法
我认为这个问题的主要原因是,当我第一次创建文件时,创建者应用程序名称为456,之后当我尝试向文件中写入更多信息时,应用程序名称为856,因此应用程序856无法写入由应用程序456创建的文件。
问题
1.我如何使用相同的应用程序名称启动应用程序,以便Android允许我第二次写入文件。 2.或者问题的主要原因不是每次应用程序都会获得随机名称。

只是一個小提示,您也可以通過liblog將日誌消息發送到logcat。 - ba__friend
3
在您的make文件中需引入log.h文件和liblog库,并使用__android_log_write()函数进行编码。以下是详细说明的一篇博客文章:http://blog.blackwhale.at/2009/08/android-ndk-logging/ - ba__friend
@ba__friend 感谢您的支持,您的回答对我非常有用,我从您的评论中学到了新的东西,但实际上并不是我想要的,我需要将其写入 Log.txt。 - Viktor Apoyan
检查fopen是否失败:if (pFile == NULL) perror("fopen"); - pmg
2个回答

1

你的代码在我的模拟器上出现了错误。但是你说:

当我第一次运行Android应用程序时,一切都很好,我可以在Log.txt文件中看到日志

也许你可以给我们发送更多的代码,这样我们就可以重现这个错误。
以下是我尝试重现你的问题:

#include<stdio.h>
#include<jni.h>
#include<android/log.h>//allow android logging
#include<errno.h>//for errors
#include<string.h>

#define  LOG_TAG    "DEO MSG"//all my logs are labeled with this
#define  LOGI(...)  __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__)
#define  LOGE(...)  __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__)

void Java_com_deo_MyActivity_writeLogFileUsingC(JNIEnv * env, jobject thisObject)
{   char filename[]="/data/LogTest/Log.txt";
    LOGE("native method started");//is used exactly like the usual printf()
    FILE * pFile;
    LOGE("trying to open file for writing");
    pFile= fopen(filename, "w");
    if(pFile==NULL)
    {
        LOGE("Failed to open the file %s in mode 'w'.(DETAILS)%s ",filename,strerror(errno));
    }
    else
    {
        LOGE("trying to write to file");
        fprintf(pFile,"logExample  "); //example of a log.
        fclose(pFile);//safely close our file
        LOGE("file writing done");
    }
}

它在logcat中生成的错误是

ERROR/DEO MSG(816): Failed to open the file /data/LogTest/Log.txt in mode 'w'.(DETAILS)No such file or directory

我认为你的代码问题可能与权限有关。请更详细地描述一下。
PS:

  • 个人而言,我更喜欢使用logcat进行调试,而不是日志文件。


0

我认为你没有权限在那个文件夹中写入。请阅读这里的答案。要么使用SDK卡,要么使用应用程序目录来存储文件。

Android NDK中的文件操作


我喜欢这个链接。Android NDK中的文件操作。 - Dr Deo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接