Skip to content

Instantly share code, notes, and snippets.

@rui314
Last active June 2, 2016 22:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rui314/85480bac012b7e886ca98d2806465667 to your computer and use it in GitHub Desktop.
Save rui314/85480bac012b7e886ca98d2806465667 to your computer and use it in GitHub Desktop.
mycp.c
#include <stdio.h>
#include <stdlib.h>
#include <sys/sendfile.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#define _GNU_SOURCE
#include <fcntl.h>
static int openfile(char *path, int flags, mode_t mode) {
int fd = open(path, flags, mode);
if (fd == -1) {
perror("open failed");
exit(1);
}
return fd;
}
static off_t filesize(int fd) {
struct stat st;
if (fstat(fd, &st) == -1) {
perror("fstat failed");
exit(1);
}
return st.st_size;
}
int main(int argc, char **argv) {
if (argc != 3) {
fprintf(stderr, "Usage: %s SOURCE DEST\n", argv[0]);
return 1;
}
int in = openfile(argv[1], O_RDONLY, 0);
int out = openfile(argv[2], O_WRONLY | O_CREAT, 0644);
off_t len = filesize(in);
if (sendfile(out, in, NULL, len) == -1) {
perror("sendfile failed");
exit(1);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment