uuprog
diff cp.c @ 0:4f628556fa3e
uuprog initial commit
author | John Tsiombikas <nuclear@member.fsf.org> |
---|---|
date | Thu, 25 Aug 2011 08:53:01 +0300 |
parents | |
children |
line diff
1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/cp.c Thu Aug 25 08:53:01 2011 +0300 1.3 @@ -0,0 +1,60 @@ 1.4 +/*! cc -o cp cp.c */ 1.5 +#include <stdio.h> 1.6 +#include <string.h> 1.7 +#include <errno.h> 1.8 +#include <unistd.h> 1.9 +#include <sys/types.h> 1.10 +#include <sys/stat.h> 1.11 + 1.12 +int copy_file(const char *sname, const char *dname); 1.13 + 1.14 +char buf[4096]; 1.15 + 1.16 +int main(int argc, char **argv) 1.17 +{ 1.18 + int i, src_count = argc - 2; 1.19 + 1.20 + if(src_count > 1) { 1.21 + struct stat st; 1.22 + char *to_dir = argv[argc - 1]; 1.23 + 1.24 + if(stat(to_dir, &st) == -1) { 1.25 + fprintf(stderr, "failed to stat %s: %s\n", to_dir, strerror(errno)); 1.26 + return 1; 1.27 + } 1.28 + 1.29 + for(i=0; i<src_count; i++) { 1.30 + sprintf(buf, "%s/%s", to_dir, argv[i+1]); 1.31 + if(copy_file(argv[i+1], buf) == -1) { 1.32 + return 1; 1.33 + } 1.34 + } 1.35 + return 0; 1.36 + } 1.37 + 1.38 + return copy_file(argv[1], argv[2]) == -1 ? 1 : 0; 1.39 +} 1.40 + 1.41 +int copy_file(const char *sname, const char *dname) 1.42 +{ 1.43 + FILE *src, *dst; 1.44 + size_t brd; 1.45 + 1.46 + if(!(src = fopen(sname, "rb"))) { 1.47 + fprintf(stderr, "failed to open source file %s: %s\n", sname, strerror(errno)); 1.48 + return -1; 1.49 + } 1.50 + if(!(dst = fopen(dname, "wb"))) { 1.51 + fclose(src); 1.52 + fprintf(stderr, "failed to open destination file %s: %s\n", dname, strerror(errno)); 1.53 + return -1; 1.54 + } 1.55 + 1.56 + while((brd = fread(buf, 1, sizeof buf, src)) > 0) { 1.57 + fwrite(buf, 1, brd, dst); 1.58 + } 1.59 + 1.60 + fclose(dst); 1.61 + fclose(src); 1.62 + return 0; 1.63 +}