简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM