Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I copy a file on Unix using C?

Tags:

c

unix

copy

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

like image 700
Motti Avatar asked Feb 01 '10 21:02

Motti


People also ask

How do you copy a file in Unix?

You can use the shell commands cp or pax or the TSO/E command OCOPY to copy files within the z/OS UNIX file system. Using the shell: Use the cp shell command to copy: One file to another file in the working directory, or to a new file in another directory.

How copy file using cp in Linux?

Syntax: cp [OPTION] Source Destination cp [OPTION] Source Directory cp [OPTION] Source-1 Source-2 Source-3 Source-n Directory First and second syntax is used to copy Source file to Destination file or Directory. Third syntax is used to copy multiple Sources(files) to Directory.

How do I make a copy of a file in Linux?

To copy a file, specify “cp” followed by the name of a file to copy. Then, state the location at which the new file should appear. The new file does not need to have the same name as the one you are copying. The “source” refers to the file or folder you want to move.


1 Answers

There is no need to either call non-portable APIs like sendfile, or shell out to external utilities. The same method that worked back in the 70s still works now:

#include <fcntl.h> #include <unistd.h> #include <errno.h>  int cp(const char *to, const char *from) {     int fd_to, fd_from;     char buf[4096];     ssize_t nread;     int saved_errno;      fd_from = open(from, O_RDONLY);     if (fd_from < 0)         return -1;      fd_to = open(to, O_WRONLY | O_CREAT | O_EXCL, 0666);     if (fd_to < 0)         goto out_error;      while (nread = read(fd_from, buf, sizeof buf), nread > 0)     {         char *out_ptr = buf;         ssize_t nwritten;          do {             nwritten = write(fd_to, out_ptr, nread);              if (nwritten >= 0)             {                 nread -= nwritten;                 out_ptr += nwritten;             }             else if (errno != EINTR)             {                 goto out_error;             }         } while (nread > 0);     }      if (nread == 0)     {         if (close(fd_to) < 0)         {             fd_to = -1;             goto out_error;         }         close(fd_from);          /* Success! */         return 0;     }    out_error:     saved_errno = errno;      close(fd_from);     if (fd_to >= 0)         close(fd_to);      errno = saved_errno;     return -1; } 
like image 129
caf Avatar answered Sep 17 '22 19:09

caf