是查看一个目录,根据文件的数目,启动相应的进程数

//题目是查看一个目录,根据文件的数目,启动相应的进程数,
/*
将文件拷贝到另一目录中去。

  我自己做的代码如下:
  有段错误,我找不出来,我在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;
}


 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值