实现:我这里是实现的是和linux终端中的cp指令类似的功能,将多个文件同时拷贝到指定的目录中。也就是说利用main函数传参,在执行程序的命令后输入拷贝的文件和目标目录。可以看最后的运行效果图。
代码实现:
#include <stdio.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
/*目标缓冲区要足够大,不然sprintf有警告*/
char buff[2][2048];
typedef struct filepath{
char src[1024];
char dest[1024];
}PATH;
pthread_t pth1,pth2;
/*多线程公用函数*/
void *pthread_task(void *argv){
PATH *p = (PATH*)argv;
int fd1 = open(p->src,O_RDONLY);
if(fd1 < 0){
perror("open");
pthread_exit(NULL);
}
int fd2 = open(p->dest,O_CREAT|O_WRONLY|O_TRUNC,0777);
if(fd2 < 0){
perror("open");
pthread_exit(NULL);
}
char c;
int i = 0;
struct stat s;
stat(p->src,&s);
while(read(fd1,&c,sizeof(char))){
if(write(fd2,&c,sizeof(char)) > 0){
if(pthread_self() == pth1){
sprintf(buff[0],"%s拷贝中[%.1lf%%]",p->src,(double)i++/s.st_size*100);
}
else if(pthread_self() == pth2){
sprintf(buff[1],"%s拷贝中[%.1lf%%]",p->src,(double)i++/s.st_size*100);
}
printf("%s,%s\r",buff[0],buff[1]);
continue;
}
if(pthread_self() == pth1){
sprintf(buff[0],"%s拷贝失败",p->src);
}
else if(pthread_self() == pth2){
sprintf(buff[1],"%s拷贝失败",p->src);
}
printf("%s,%s\r",buff[0],buff[1]);
close(fd1);
close(fd2);
pthread_exit(NULL);
}
if(pthread_self() == pth1){
sprintf(buff[0],"%s拷贝完成[%.1lf%%]",p->src,(double)i++/s.st_size*100);
}
else if(pthread_self() == pth2){
sprintf(buff[1],"%s拷贝完成[%.1lf%%]",p->src,(double)i++/s.st_size*100);
}
printf("%s,%s\r",buff[0],buff[1]);
close(fd1);
close(fd2);
pthread_exit(NULL);
}
int main(int argc,char *argv[]){
PATH p1;
strcpy(p1.src,argv[1]);
strcpy(p1.dest,argv[3]);
char *find = strrchr(p1.src,'/');
strcat(p1.dest,find);
if(0 != pthread_create(&pth1,NULL,pthread_task,&p1)){
perror("pthread_create");
return -1;
}
PATH p2;
strcpy(p2.src,argv[2]);
strcpy(p2.dest,argv[3]);
find = strrchr(p2.src,'/');
strcat(p2.dest,find);
if(0 != pthread_create(&pth2,NULL,pthread_task,&p2)){
perror("pthread_create");
return -1;
}
pthread_join(pth1,NULL);
pthread_join(pth2,NULL);
putchar('\n');
return 0;
}
运行效果: