//题目是查看一个目录,根据文件的数目,启动相应的进程数,
/*
将文件拷贝到另一目录中去。
我自己做的代码如下:
有段错误,我找不出来,我在linux下做的
*/
//#include<iostream>
#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<dirent.h>
#include<pthread.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<sys/types.h>
//using namespace std;
const int M = 20;
void *copy(void *param)
{
struct dirent *pdirent;
FILE *fp1;
FILE *fp2;
char filename[200] = {'\0'};
int times;
char buff[1024];
char str[200];
pdirent = (struct dirent *)param;
if (NULL == pdirent)
{
printf("copy-(NULL == pdirent)\n");
return;
}
if (NULL == pdirent->d_name)
{
printf("copy-(NULL == pdirent)\n");
return;
}
fp1 = fopen(pdirent->d_name,"r");
if (NULL == fp1)
{
printf("copy-(NULL == fp1)\n");
return;
}
printf("%s\n", pdirent->d_name);
// cout<<pdirent->d_name<<endl;
strcpy(str,"/home/lxx/code3/");
strcat(str,pdirent->d_name);
sprintf(filename,"%s",str);
printf("%s\n", filename);
creat(filename,0777);
fp2 = fopen(filename,"w");
if (NULL == fp2)
{
fclose(fp1);
printf("copy-(NULL == fp2)\n");
return;
}
while((times = fread(buff,1,1024,fp1)) != 0)
{
fwrite(buff,1,times,fp2);
}
fclose(fp1);
fclose(fp2);
}
int main()
{
int i = 0;
int j;
DIR *pdir;
struct dirent *pdirent;
pthread_t tt[M];
pdir = opendir("/home/lxx/code2");
if (NULL == pdir)
{
printf("main-(NULL == pdir)\n");
return -1;
}
while(((pdirent = readdir(pdir)) != NULL))
{
struct stat st;
memset(&st,0,sizeof(st));
// cout<<pdirent->d_name<<endl;
if (NULL == pdirent)
{
printf("main-(NULL == pdirent)\n");
continue;
}
if (NULL == pdirent->d_name)
{
printf("main-(NULL == pdirent)\n");
continue;
}
stat(pdirent->d_name,&st);
printf("%s\n", pdirent->d_name);
pthread_create(&tt[i],NULL,copy,(void*)pdirent);
i++;
sleep(1);
}
sleep(3); // jernymy for dealy
for(j = 0;j<i; j++) // jernymy, here is "Segmentation fault"
{
pthread_join(tt[j],NULL);
}
return 0;
}
是查看一个目录,根据文件的数目,启动相应的进程数
最新推荐文章于 2022-06-21 17:37:02 发布