uuprog

view 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 source
1 /*! cc -o cp cp.c */
2 #include <stdio.h>
3 #include <string.h>
4 #include <errno.h>
5 #include <unistd.h>
6 #include <sys/types.h>
7 #include <sys/stat.h>
9 int copy_file(const char *sname, const char *dname);
11 char buf[4096];
13 int main(int argc, char **argv)
14 {
15 int i, src_count = argc - 2;
17 if(src_count > 1) {
18 struct stat st;
19 char *to_dir = argv[argc - 1];
21 if(stat(to_dir, &st) == -1) {
22 fprintf(stderr, "failed to stat %s: %s\n", to_dir, strerror(errno));
23 return 1;
24 }
26 for(i=0; i<src_count; i++) {
27 sprintf(buf, "%s/%s", to_dir, argv[i+1]);
28 if(copy_file(argv[i+1], buf) == -1) {
29 return 1;
30 }
31 }
32 return 0;
33 }
35 return copy_file(argv[1], argv[2]) == -1 ? 1 : 0;
36 }
38 int copy_file(const char *sname, const char *dname)
39 {
40 FILE *src, *dst;
41 size_t brd;
43 if(!(src = fopen(sname, "rb"))) {
44 fprintf(stderr, "failed to open source file %s: %s\n", sname, strerror(errno));
45 return -1;
46 }
47 if(!(dst = fopen(dname, "wb"))) {
48 fclose(src);
49 fprintf(stderr, "failed to open destination file %s: %s\n", dname, strerror(errno));
50 return -1;
51 }
53 while((brd = fread(buf, 1, sizeof buf, src)) > 0) {
54 fwrite(buf, 1, brd, dst);
55 }
57 fclose(dst);
58 fclose(src);
59 return 0;
60 }