【问题标题】:How to copy file from one directory to another using native code in Android?如何使用Android中的本机代码将文件从一个目录复制到另一个目录?
【发布时间】:2012-03-21 11:40:53
【问题描述】:

我想在我的 Native C 程序中将文件从一个目录复制到另一个目录。 我尝试使用system 函数,但它不起作用。

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

另外我想知道仿生libc甚至支持system函数。

任何帮助将不胜感激。

【问题讨论】:

  • Android 是 Java,那么 Native C 是什么意思?
  • @WaynnLue 我在这里使用的是 Android NDK
  • 你考虑过在java端做吗?
  • 不,我想在本机代码端(C 端)执行此操作

标签: android c linux android-ndk


【解决方案1】:

Android shell 没有 cp 命令。所以如果可能,请尝试cat source_file > dest_file

或者直接使用这段代码,

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);
  }

也提到了

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

AndroidManifest.xml 文件中..

编辑:

您也可以使用dd if=source_file of=dest_file

不需要重定向支持。

【讨论】:

  • 另外我想知道仿生libc甚至支持系统功能。
  • 我还为 cp 命令安装了忙箱。 cp 命令正在 Android shell 上运行,但我想从本机 C 代码调用此命令
  • 我在c代码中使用了execl()命令来执行adb命令。
  • 感谢回复但在这里 system("cp /mnt/test /mnt/test2");也返回一些错误代码值。所以系统功能可能正在工作。我还安装了busy-box,我直接在Shell上执行了cp命令,然后它工作正常
猜你喜欢
  • 2013-10-24
  • 2012-02-15
  • 2011-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-18
  • 2012-03-24
相关资源
最近更新 更多