在Android中用c语言将文件从sdcard位置复制到另一个位置

Copy a file from sdcard location to another location in c language in Android

我写了一段代码,用 C 语言在 Android 设备中将文本文件从一个位置 (/mnt/sdcard/Appfolder/filename.txt) 复制到另一个位置 (/data/test/log.txt) 并使用 ndk.

我不知道文件的名称,所以我将 *.txt 作为源文件。

int copy_file(char* src, char *dest) {

  FILE *p,*q;
  char *file1,*file2;
  int ch;

  file1 = src;
  p=fopen(file1,"r");
  if(p==NULL){
      printf("cannot open %s",file1);
      exit(0);
  }

   file2 = dest;
  q=fopen(file2,"w");
  if(q==NULL){
      printf("cannot open %s",file2);
      exit(0);
  }
  while((ch=getc(p))!=EOF)
      putc(ch,q);
  printf("\nCOMPLETED");
  fclose(p);
  fclose(q);
 return 0;
}

但是我收到这个错误:

cannot open /mnt/sdcard/Appfolder/<filename.txt>

我做错了什么?

文件属性为660。

您可以使用 system() 函数来执行此操作。例如,对于Windows,您可以只使用复制命令来复制txt 文件。

system("copy C:\src\dir\*.txt C:\dest\dir\");

或带变量(伪代码):

#define PATH_MAX        4096


char command[MAX_PATH * 2 + 6];
char *file1 = src, *file2 = dest;


strcpy(command, "copy ");
strcat(command, file1);
strcat(command, " ");
strcat(command, file2);

system(command);