How can I copy a file on Unix using C?

前端 未结 8 713
说谎
说谎 2020-11-27 12:39

I\'m looking for the Unix equivalent of Win32\'s CopyFile, I don\'t want to reinvent the wheel by writing my own version.

8条回答
  •  悲&欢浪女
    2020-11-27 13:05

    Another variant of the copy function using normal POSIX calls and without any loop. Code inspired from the buffer copy variant of the answer of caf. Warning: Using mmap can easily fail on 32 bit systems, on 64 bit system the danger is less likely.

    #include 
    #include 
    #include 
    #include 
    
    int cp(const char *to, const char *from)
    {
      int fd_from = open(from, O_RDONLY);
      if(fd_from < 0)
        return -1;
      struct stat Stat;
      if(fstat(fd_from, &Stat)<0)
        goto out_error;
    
      void *mem = mmap(NULL, Stat.st_size, PROT_READ, MAP_SHARED, fd_from, 0);
      if(mem == MAP_FAILED)
        goto out_error;
    
      int fd_to = creat(to, 0666);
      if(fd_to < 0)
        goto out_error;
    
      ssize_t nwritten = write(fd_to, mem, Stat.st_size);
      if(nwritten < Stat.st_size)
        goto out_error;
    
      if(close(fd_to) < 0) {
        fd_to = -1;
        goto out_error;
      }
      close(fd_from);
    
      /* Success! */
      return 0;
    }
    out_error:;
      int saved_errno = errno;
    
      close(fd_from);
      if(fd_to >= 0)
        close(fd_to);
    
      errno = saved_errno;
      return -1;
    }
    

    EDIT: Corrected the file creation bug. See comment in http://stackoverflow.com/questions/2180079/how-can-i-copy-a-file-on-unix-using-c/2180157#2180157 answer.

提交回复
热议问题