V3FIT
copy_file.c
Go to the documentation of this file.
1 //******************************************************************************
8 
9 #include <sys/errno.h>
10 
11 #if defined(__APPLE__)
12 #include <copyfile.h>
13 #else
14 
15 #include <fcntl.h>
16 #include <sys/sendfile.h>
17 #include <sys/stat.h>
18 
20 #define COPYFILE_ALL 0
21 
22 //------------------------------------------------------------------------------
34 //------------------------------------------------------------------------------
35 size_t copyfile(const char *src, const char *dest, const int unused_1, const int unused_2) {
36 
37  // Open source file as read only.
38  int read_file = open(src, O_RDONLY);
39 
40  // Need the permissions and file size values of the source file.
41  struct stat stat_buffer;
42  fstat(read_file, &stat_buffer);
43 
44  // Open the destination file as write only with the same permissions as the
45  // source file.
46  int write_file = open(dest, O_WRONLY | O_CREAT, stat_buffer.st_mode);
47 
48  // Copy the file.
49  off_t bytesCopied = 0;
50  size_t error = sendfile(write_file, read_file, &bytesCopied, stat_buffer.st_size);
51 
52  // Close file handles.
53  close(read_file);
54  close(write_file);
55 }
56 
57 #endif
58 
59 //------------------------------------------------------------------------------
68 //------------------------------------------------------------------------------
69 int copy_file_c(const char *src, const char *dest) {
70  if (copyfile(src, dest, 0, COPYFILE_ALL) < 0) {
71  return errno;
72  } else {
73  return 0;
74  }
75 }
COPYFILE_ALL
#define COPYFILE_ALL
Flag to copy the enture file.
Definition: copy_file.c:20
copy_file_c
int copy_file_c(const char *src, const char *dest)
Copy a file from the source to the destination.
Definition: copy_file.c:69
copyfile
size_t copyfile(const char *src, const char *dest, const int unused_1, const int unused_2)
Copy a file from the source to the destination.
Definition: copy_file.c:35