C函数在UNIX中复制目录:文件无法复制

时间:2013-04-29 23:27:05

标签: c unix

我正在尝试在C中编写一个函数来将目录的内容复制到另一个目录。以下是我到目前为止的情况:

void *copydirectory(void *arg1, void *arg2) 
{
  int error;
  struct dirent *direntp;
  DIR *dirp_source, *dirp_destination;
  char *source, *destination;
  copy_t copy;
  char filename[MAXNAME];

  // Set directory arguments
  source = arg1;
  destination = arg2;
  fprintf(stderr, "Source directory is %s and destination directory is %s\n", source, destination);

  // Open directories
  if ((dirp_source = opendir(source)) == NULL)
  {
      fprintf(stderr, "Failed to open %s\n", source);
      return 1;
  }

  if ((dirp_destination = opendir(destination)) == NULL)
  {
      perror("Failed to open destination directory");
      return 1;
  }

  // Read files in directory
  while ((direntp = readdir(dirp_source)) != NULL)
  {
      copy.tid = pthread_self();
      fprintf(stderr, "now at line 64\n");

      // Copy source filename
      if (snprintf(filename, MAXNAME, direntp->d_name) == MAXNAME)
      {
      fprintf(stderr, "Input filename %s is too long", direntp->d_name);
      continue;
      } 

      fprintf(stderr, "now at line 73\n");

      fprintf(stderr, "%s\n", filename);
      // Open file for reading
      if ((copy.args[0] = open(filename, R_FLAGS)) == -1)
      {
      fprintf(stderr, "Failed to open source file %s: %s\n", filename, strerror(errno));
      continue;
      }

      // Create destination filename for writing
      if (snprintf(filename, MAXNAME, "%s", direntp->d_name) == MAXNAME)
      {
      fprintf(stderr, "Output filename %s is too long\n", direntp->d_name);
      continue;
      }

      fprintf(stderr, "%s\n", filename);  
      // Open file for writing
      if ((copy.args[1] = open(filename, W_FLAGS, W_PERMS)) == -1)
      {
      fprintf(stderr, "Failed to open destination file %s: %s\n", filename,      strerror(errno));
      continue;
      }

      if (error = pthread_create((&copy.tid), NULL, copyfilepass, copy.args))
      {
      fprintf(stderr, "Failed to create thread: %s\n", strerror(error));
      copy.tid = pthread_self();
      }
  }

  // Close directory
  while ((closedir(dirp_source) == -1) && (errno = EINTR));

  fprintf(stderr, "Successfully copied all files in directory \n");

}

现在,为了测试,我在名为dir1和dir2的文件夹中只有2个目录。 dir1包含3个文件:file1,file2,file3。 但是,当我编译并运行代码时,我会收到以下消息:

./
./
Failed to open destination file .: is a directory
Failed to open source file file2: No such file or directory
Failed to open source file file3: No such file or directory
../
../
Failed to open destination file .: is a directory
Failed to open source file file1: No such file or directory

任何人都有什么建议吗?

1 个答案:

答案 0 :(得分:1)

  

无法打开目标文件。:是目录

您会看到这一点,因为您的源目录分别包含名为"."".."的链接及其父目录。您应该专门检查并避免这些条目。

  

无法打开源文件file2:没有这样的文件或目录

您看到了这一点,因为您尝试在进程的当前工作目录中打开一个名为"file2"的文件,但该文件不存在 - 您所访问的文件位于源目录中。您需要构建文件名,并考虑到这一点:

// Copy source filename
if (snprintf(filename, MAXNAME, "%s/%s", source, direntp->d_name) == MAXNAME)