【多线程】

#include 
#include 
#include 
#include 
#include 

#define BUFFER_SIZE 128

// 用于传递线程参数的结构体
struct ThreadArgs {
    const char *srcfile;
    const char *dstfile;
    int start;
    int len;
};

// 获取文件长度的函数
int get_file_len(const char *srcfile) {
    int srcfd;
    if ((srcfd = open(srcfile, O_RDONLY)) == -1) {
        perror("打开源文件错误");
        return -1;
    }

    int len = lseek(srcfd, 0, SEEK_END);
    close(srcfd);

    return len;
}

// 文件拷贝函数
void *file_copy(void *args) {
    struct ThreadArgs *threadArgs = (struct ThreadArgs *)args;

    int srcfd, dstfd;
    if ((srcfd = open(threadArgs->srcfile, O_RDONLY)) == -1) {
        perror("打开源文件错误");
        pthread_exit(NULL);
    }

    if ((dstfd = open(threadArgs->dstfile, O_WRONLY)) == -1) {
        perror("打开目标文件错误");
        close(srcfd);
        pthread_exit(NULL);
    }

    lseek(srcfd, threadArgs->start, SEEK_SET);
    lseek(dstfd, threadArgs->start, SEEK_SET);

    char buf[BUFFER_SIZE];
    int res, sum = 0;

    while (1) {
        res = read(srcfd, buf, sizeof(buf));
        sum += res;

        if (sum >= threadArgs->len || res == 0) {
            write(dstfd, buf, res - (sum - threadArgs->len));
            break;
        }

        write(dstfd, buf, res);
    }

    close(srcfd);
    close(dstfd);
    pthread_exit(NULL);
}

int main(int argc, const char *argv[]) {
    if (argc != 3) {
        printf("输入文件错误\n");
        printf("用法:./a.out 源文件 目标文件\n");
        return -1;
    }

    int len = get_file_len(argv[1]);

    pthread_t thread1, thread2;

    struct ThreadArgs args1 = {argv[1], argv[2], 0, len / 2};
    struct ThreadArgs args2 = {argv[1], argv[2], len / 2, len - len / 2};

    // 创建线程1
    if (pthread_create(&thread1, NULL, file_copy, (void *)&args1) != 0) {
        perror("创建线程错误");
        return -1;
    }

    // 创建线程2
    if (pthread_create(&thread2, NULL, file_copy, (void *)&args2) != 0) {
        perror("创建线程错误");
        return -1;
    }

    // 等待两个线程完成
    if (pthread_join(thread1, NULL) != 0 || pthread_join(thread2, NULL) != 0) {
        perror("等待线程错误");
        return -1;
    }

    printf("拷贝成功\n");

    return 0;
}

你可能感兴趣的:(算法,数据结构)