cp.cpp
1 #include "coreutils.h" 2 3 #include <SD.h> 4 #include <stdio.h> 5 #include <string.h> 6 7 extern char g_cwd[]; 8 9 static void resolve(const char *path, char *out, size_t cap) { 10 if (path[0] == '/') 11 strlcpy(out, path, cap); 12 else 13 snprintf(out, cap, "%s%s%s", 14 g_cwd, (strcmp(g_cwd, "/") == 0) ? "" : "/", path); 15 } 16 17 int programs::coreutils::cmd_cp(int argc, char **argv) { 18 if (argc < 3) { printf("usage: cp <src> <dst>\n"); return 1; } 19 20 char src[128], dst[128]; 21 resolve(argv[1], src, sizeof(src)); 22 resolve(argv[2], dst, sizeof(dst)); 23 24 File in = SD.open(src, FILE_READ); 25 if (!in) { printf("cp: cannot open %s\n", argv[1]); return 1; } 26 27 File out = SD.open(dst, FILE_WRITE); 28 if (!out) { in.close(); printf("cp: cannot create %s\n", argv[2]); return 1; } 29 30 char buf[512]; 31 size_t total = 0; 32 while (in.available()) { 33 int n = in.readBytes(buf, sizeof(buf)); 34 if (n <= 0) break; 35 out.write((uint8_t *)buf, n); 36 total += n; 37 } 38 39 in.close(); 40 out.close(); 41 printf("copied %s -> %s (%u bytes)\n", argv[1], argv[2], (unsigned)total); 42 return 0; 43 }