1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
| #include <head.h> typedef struct { const char* src; const char* dest; int start; int len; } file_t; int get_file_len(const char* file) { int fd, len; if ((fd = open(file, O_RDONLY)) == -1) PRINT_ERR("open error"); len = lseek(fd, 0, SEEK_END); close(fd); return len; } int init_src_file(const char* file) { int fd; if ((fd = open(file, O_WRONLY | O_CREAT | O_TRUNC, 0666)) == -1) PRINT_ERR("open error");
close(fd); return 0; } int copy_file(const char* src, const char* dest, int start, int len) { char s[20]; int fd1, fd2; int ret, count = 0; if ((fd1 = open(src, O_RDONLY)) == -1) PRINT_ERR("open src error"); if ((fd2 = open(dest, O_WRONLY)) == -1) PRINT_ERR("open dest error"); lseek(fd1, start, SEEK_SET); lseek(fd2, start, SEEK_SET); while (count < len) { ret = read(fd1, s, sizeof(s)); count += ret; write(fd2, s, ret); } close(fd1); close(fd2); return 0; } void* thread(void* arg) { file_t *f = (file_t *)arg; copy_file(f->src, f->dest, f->start, f->len); pthread_exit(NULL); }
int main(int argc, const char* argv[]) { int len; pid_t pid; if (argc != 3) { fprintf(stderr, "input error,try again\n"); fprintf(stderr, "usage:./a.out srcfile destfile\n"); return -1; } len = get_file_len(argv[1]);
init_src_file(argv[2]);
pthread_t tid1, tid2; file_t f[] = { [0] = { .src = argv[1], .dest = argv[2], .start = 0, .len = len / 2, }, [1] = { .src = argv[1], .dest = argv[2], .start = len/2, .len = (len - len / 2), }, }; if ((errno = pthread_create(&tid1, NULL, thread, (void *)&f[0]))) PRINT_ERR("pthread_create error"); if ((errno = pthread_create(&tid2, NULL, thread, (void *)&f[1]))) PRINT_ERR("pthread_create error");
pthread_join(tid1, NULL); pthread_join(tid2, NULL); return 0; }
|