From 66f6055a133e6cbeee28b714d2bfbdefa769ccf8 Mon Sep 17 00:00:00 2001 From: Jonas 'Sortie' Termansen Date: Mon, 21 Nov 2011 14:57:02 +0100 Subject: [PATCH] Added cp(1). --- utils/Makefile | 1 + utils/cp.cpp | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+) create mode 100644 utils/cp.cpp diff --git a/utils/Makefile b/utils/Makefile index daad2298..137ac265 100644 --- a/utils/Makefile +++ b/utils/Makefile @@ -6,6 +6,7 @@ INITRDDIR:=../initrd LOCALBINARIES:=\ init \ cat \ +cp \ sh \ mxsh \ clear \ diff --git a/utils/cp.cpp b/utils/cp.cpp new file mode 100644 index 00000000..a43002ba --- /dev/null +++ b/utils/cp.cpp @@ -0,0 +1,38 @@ +#include +#include +#include + +bool writeall(int fd, const void* buffer, size_t len) +{ + const char* buf = (const char*) buffer; + while ( len ) + { + ssize_t byteswritten = write(fd, buf, len); + if ( byteswritten < 0 ) { return false; } + buf += byteswritten; + len -= byteswritten; + } + + return true; +} + +int main(int argc, char* argv[]) +{ + if ( argc != 3 ) { printf("usage: %s \n", argv[0]); return 0; } + + int fromfd = open(argv[1], O_RDONLY); + if ( fromfd < 0 ) { printf("%s: cannot open for reading: %s\n", argv[0], argv[1]); return 1; } + + int tofd = open(argv[2], O_WRONLY | O_TRUNC | O_CREAT, 0777); + if ( tofd < 0 ) { printf("%s: cannot open for writing: %s\n", argv[0], argv[2]); return 1; } + + while ( true ) + { + const size_t BUFFER_SIZE = 4096; + char buffer[BUFFER_SIZE]; + ssize_t bytesread = read(fromfd, buffer, BUFFER_SIZE); + if ( bytesread < 0 ) { printf("%s: read failed: %s\n", argv[0], argv[1]); return 1; } + if ( bytesread == 0 ) { return 0; } + if ( !writeall(tofd, buffer, bytesread) ) { printf("%s: write failed: %s\n", argv[0], argv[2]); return 1; } + } +}