user1089679
user1089679

Reputation: 2368

How to copy file from one directory to another using native code in Android?

I want to copy file from on directory to another in my Native C program. I tried using system function but it's not working.

system("cp /mnt/test /mnt/test2"); // It's not working

Also I want to know that even system function is supported in bionic libc.

Any help would be appreciated.

Upvotes: 0

Views: 3587

Answers (1)

user370305
user370305

Reputation: 109257

The Android shell does not have the cp command. So if possible try cat source_file > dest_file .

Or just use this code,

FILE *from, *to;
  char ch;


  if(argc!=3) {
    printf("Usage: copy <source> <destination>\n");
    exit(1);
  }

  /* open source file */
  if((from = fopen("Source File", "rb"))==NULL) {
    printf("Cannot open source file.\n");
    exit(1);
  }

  /* open destination file */
  if((to = fopen("Destination File", "wb"))==NULL) {
    printf("Cannot open destination file.\n");
    exit(1);
  }

  /* copy the file */
  while(!feof(from)) {
    ch = fgetc(from);
    if(ferror(from)) {
      printf("Error reading source file.\n");
      exit(1);
    }
    if(!feof(from)) fputc(ch, to);
    if(ferror(to)) {
      printf("Error writing destination file.\n");
      exit(1);
    }
  }

  if(fclose(from)==EOF) {
    printf("Error closing source file.\n");
    exit(1);
  }

  if(fclose(to)==EOF) {
    printf("Error closing destination file.\n");
    exit(1);
  }

Also mentioned

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>

in AndroidManifest.xml file..

EDIT:

You can use also dd if=source_file of=dest_file.

Redirection support is not needed.

Upvotes: 1

Related Questions