Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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