Skip to content

Instantly share code, notes, and snippets.

@gustavorv86
Last active August 13, 2019 11:15
Show Gist options
  • Save gustavorv86/595127b9c22144f92b74f71a36098a4c to your computer and use it in GitHub Desktop.
Save gustavorv86/595127b9c22144f92b74f71a36098a4c to your computer and use it in GitHub Desktop.
POSIX GNU/Linux efficient copy file.
/**
* Copy the 'source' file to 'dest'. If 'dest' exists it will be
* overwritten.
*
* @param source Path to the source file.
* @param dest Path to the destination file.
* @return Number of bytes copied or -1 if cannot copy
* file.
*/
int file_copy(char * source, char * dest)
{
int fd_input, fd_output, rval;
off_t n_bytes = 0;
struct stat s_stat = {0};
if ((fd_input = open(source, O_RDONLY)) == -1)
{
return -1;
}
if ((fd_output = creat(dest, 0660)) == -1)
{
close(fd_input);
return -1;
}
fstat(fd_input, &s_stat);
rval = sendfile(fd_output, fd_input, &n_bytes, s_stat.st_size);
close(fd_input);
close(fd_output);
return rval;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment