-2

android is a kind of linux,and it must support the posix.But,when it seems not support the syscall,open(). Here is the code for testing,and i compile it via NDK:

#include <unistd.h>
#include <stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>

void main(){
    int fd;
    char pathname[128] = "/data/pwrite.txt";
    fd = open(pathname, O_WRONLY);
    if(fd==-1){
        printf("open fail.\n");

    }
    perror("/data/pwrite.txt");
}

and the following is the prompt that comes from android:

kaiwii@ubuntu:~$ adb shell /data/pwrite/test1
open fail.
/data/pwrite.txt: No such file or directory
kaiwii ho
  • 1,367
  • 7
  • 21
  • 40
  • Instead of just printing `"open fail"`, print the actual error instead. You can do that either by printing out `errno` or the string returned by `strerror`, or using the `perror` function. – Some programmer dude May 28 '12 at 08:04
  • kaiwii@ubuntu:~$ adb shell /data/pwrite/test1 open fail. /data/pwrite.txt: No such file or directory – kaiwii ho May 28 '12 at 08:09
  • @Joachim Pileborg i use the perror to print the error,and the above is what it prompt.But,i feel confused that why not the open() create the file yet.thx – kaiwii ho May 28 '12 at 08:10
  • have you visited [this](http://stackoverflow.com/q/1992953/996493) ? @kaiwiiho – Lucifer May 28 '12 at 08:22
  • actucally,my question seems a little bit different from it. – kaiwii ho May 31 '12 at 10:00

2 Answers2

1

I think the problem is not the syscall open() but the fact that your are trying to access /data. This folder is accessible only for rooted mobiles or in the emulator. Have you tried to put the file into the /sdcard folder?

Blackbelt
  • 156,034
  • 29
  • 297
  • 305
1

I think that the problem is in the flags - you only use O_WRONLY. But if a file does not exist you should also create it using O_CREAT flag. So if a file does not exist you should call:

fd = open(pathname, O_WRONLY | O_CREAT);
Yury
  • 20,618
  • 7
  • 58
  • 86