C语言写一个双线程文件复制程序
时间: 2024-10-11 15:11:04 浏览: 26
在C语言中编写一个双线程文件复制程序可以利用POSIX线程库(pthread)。下面是一个简单的示例,它创建两个线程分别负责读取源文件和写入目标文件:
```c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#define BUF_SIZE 4096
char src[50], dst[50];
size_t bytes_read, bytes_written;
// 读取数据的线程函数
void* read_thread(void* arg) {
FILE *src_file = fopen(src, "rb");
if (!src_file) {
perror("Error opening source file");
return NULL;
}
while (bytes_read != EOF) {
char buffer[BUF_SIZE];
size_t read = fread(buffer, sizeof(char), BUF_SIZE, src_file);
if (read == 0)
break;
bytes_read += read;
pthread_mutex_lock(&mutex); // 线程同步
fwrite(buffer, sizeof(char), read, dst_file);
pthread_mutex_unlock(&mutex);
}
fclose(src_file);
return NULL;
}
// 写入数据的线程函数
void* write_thread(void* arg) {
FILE *dst_file = fopen(dst, "wb");
if (!dst_file) {
perror("Error opening destination file");
return NULL;
}
while (bytes_written != bytes_read) {
char buffer[BUF_SIZE];
size_t written = fread(buffer, sizeof(char), BUF_SIZE, stdin); // 模拟从缓冲区读取
if (written == 0)
break;
bytes_written += written;
pthread_mutex_lock(&mutex);
fwrite(buffer, sizeof(char), written, dst_file);
pthread_mutex_unlock(&mutex);
}
fclose(dst_file);
return NULL;
}
int main() {
pthread_mutex_init(&mutex, NULL);
printf("Enter the source file path: ");
fgets(src, sizeof(src), stdin);
src[strlen(src)-1] = '\0'; // 移除换行符
printf("Enter the destination file path: ");
fgets(dst, sizeof(dst), stdin);
dst[strlen(dst)-1] = '\0';
pthread_t reader, writer;
if (pthread_create(&reader, NULL, read_thread, NULL) || pthread_create(&writer, NULL, write_thread, NULL)) {
perror("Error creating thread");
exit(1);
}
pthread_join(reader, NULL);
pthread_join(writer, NULL);
pthread_mutex_destroy(&mutex);
return 0;
}
```
在这个例子中,`read_thread` 和 `write_thread` 分别读取源文件和将内容写入目标文件,通过共享全局变量`bytes_read` 和 `bytes_written` 来同步进程。注意,这个示例简化了输入和同步过程,实际应用中需要更完善的错误处理和用户交互。
阅读全文