android文件操作,打开,失败

时间:2012-05-28 02:55:00

标签: android linux android-ndk embedded-linux

我正在使用ndk工具链来构建以下代码来测试android文件操作的容量。 而且,在/ data中,读或写的权限无疑是好的。但是,我很困惑为什么fopen()不起作用并返回NULL。 这是代码:

#include <unistd.h>
#include <stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
void main()
{
    int fd;
    int count = 128;
    int offset = 32;
    int ret;
    char buf[1024]="hi ! this is pwrite.";
    char pathname[128] = "/data/pwrite.txt";
    /*fd = fopen(pathname, O_WRONLY);*/
    FILE *infile;
    infile = fopen(pathname, "rb");
    if(infile==NULL) printf("fopen error  \n");
    /*if(fd==-1)printf("open error \n");*/
    if((ret = pwrite(fd, buf, count, offset))==-1)
    {
        printf("pwrite error\n");
        exit(1);
    }
    else
    {
        printf("pwrite success\n");
        printf("the writed data is:%s", buf);
    }
}

当我直接在Android中运行代码时,它会提示以下内容:

# ./test
fopen error  
pwrite error

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

除了文件模式问题,

"/data/pwrite.txt"

不应该是Android应用程序用户ID,甚至(在安全设备上)adb shell用户可以访问的位置。

从大约android 2.2开始(但随时可能更改),/ data / local可用作adb shell用户的临时区域。对于应用程序中的代码,每个应用程序用户ID都有自己的包独特的私有存储区域,可以通过其中一个java级别的api调用找到 - 我认为它类似于getFilesDir() - 你真的应该使用它来实现可移植性而不是硬编码路径

WRITE_EXTERNAL_STORAGE权限仅在您希望使用“外部存储”(取决于可能焊接的设备或实际可移动卡)而非内部存储时才相关。再一次,你应该通过api调用获得设备特定路径,而不是非便携地假设它类似于/ mnt / sdcard

答案 1 :(得分:1)

您在打开文件时已经给出了rb模式,这只是意味着读取二进制文件。现在您正在执行错误的write操作。您应该按如下方式给出写入模式,

infile = fopen(pathname, "wb");