Add writing to existing files and overwriting cp
This commit is contained in:
@@ -0,0 +1,55 @@
|
||||
#include "src/lib/util.h"
|
||||
#include "src/user/syscall.h"
|
||||
|
||||
#define BLOCK_SIZE 65536
|
||||
|
||||
#define PRINT_S(s) write(1, s, sizeof(s) - 1);
|
||||
#define PRINT_D(s) write(1, s, string_length(s));
|
||||
|
||||
exit_code_t main(uint64_t argc, const char **argv) {
|
||||
if (argc != 3) {
|
||||
PRINT_S("cp: requires source and target");
|
||||
return EXIT_CODE_GENERAL_FAILURE;
|
||||
}
|
||||
|
||||
uint64_t source = open(argv[1]);
|
||||
if (source == (uint64_t)-1) {
|
||||
PRINT_S("cp: source does not exist\n");
|
||||
return EXIT_CODE_GENERAL_FAILURE;
|
||||
}
|
||||
|
||||
uint64_t target = open(argv[2]);
|
||||
if (target == (uint64_t)-1) {
|
||||
PRINT_S("cp: target does not exist\n");
|
||||
close(source);
|
||||
return EXIT_CODE_GENERAL_FAILURE;
|
||||
}
|
||||
|
||||
if (truncate(target, 0) == (uint64_t)-1) {
|
||||
close(source);
|
||||
close(target);
|
||||
return EXIT_CODE_GENERAL_FAILURE;
|
||||
}
|
||||
|
||||
static char buffer[BLOCK_SIZE];
|
||||
uint64_t bytes;
|
||||
while ((bytes = read(source, BLOCK_SIZE, buffer))) {
|
||||
if (bytes == (uint64_t)-1) {
|
||||
PRINT_S("cp: could not read file\n");
|
||||
close(source);
|
||||
close(target);
|
||||
return EXIT_CODE_GENERAL_FAILURE;
|
||||
}
|
||||
if (write(target, buffer, bytes) == (uint64_t)-1) {
|
||||
PRINT_S("cp: could not write file\n");
|
||||
close(source);
|
||||
close(target);
|
||||
return EXIT_CODE_GENERAL_FAILURE;
|
||||
}
|
||||
}
|
||||
|
||||
close(source);
|
||||
close(target);
|
||||
|
||||
return EXIT_CODE_OK;
|
||||
}
|
||||
Reference in New Issue
Block a user