Skip to content

Instantly share code, notes, and snippets.

@AlecTaylor
Created September 6, 2018 03:06
Show Gist options
  • Save AlecTaylor/b6ec70cccc6e6b45decdc5284f2482cc to your computer and use it in GitHub Desktop.
Save AlecTaylor/b6ec70cccc6e6b45decdc5284f2482cc to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
int cp(const char*, const char*);
int main(int argc, char **argv) {
if (argv[1] == NULL || argv[2] == NULL) {
printf("Usage %s <source> <destination>\n", argv[0]);
exit(2);
}
cp(argv[1], argv[2]);
}
// https://stackoverflow.com/q/2180079
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;
}
FROM frolvlad/alpine-glibc
COPY copy.c copy.c
RUN apk --no-cache add gcc libc-dev musl musl-dev && \
gcc copy.c -static -o /bin/copy -Wno-implicit-function-declaration -static-libgcc && \
ldd /bin/copy
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment