|
发表于 2009-7-24 04:31:10
|
显示全部楼层
#include <sys/types.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <pthread.h>
#include <dirent.h>
#include <string.h>
#define BUFFERSIZE 4096
#define MAXNAME 200
char buf[BUFFERSIZE];
char cor_dir[MAXNAME];
char new_fpath[MAXNAME];
void oops(char *s1,char *s2)
{
fprintf(stderr,"Error %s",s1);
perror(s2);
exit(1);
}//出错处理
char *chkdir(char dirname[])
{
if(dirname[0]!='/')
{
getcwd(cor_dir,MAXNAME);
strcat(cor_dir,"/");
if(strcmp(dirname,"./")==0)
dirname=dirname+2;
strcat(cor_dir,dirname);
return (char *)cor_dir;
}
else
return (char *)dirname;
}//更改目录名
char *getfpath(char *filename,char *dirname)
{
int num;
strcpy(new_fpath,dirname);
num=strlen(dirname);
if(*(new_fpath+num-1)!='/')
strcat(new_fpath,"/");
strcat(new_fpath,filename);
if(strlen(new_fpath)!=0)
return (char *)new_fpath;
else
return NULL;
}//创建文件地址
int main(int argc,char *argv[])
{
DIR *from_dir,*to_dir;
struct dirent *direntp;
char *filepath,*sor_dir,*des_dir,*temp;
int in_file,out_file;
int i;
printf("##\n");//测试一下
if(argc!=3)
{
printf("NO any files\n");
exit(1);
}
sor_dir=calloc(MAXNAME,sizeof(char));
des_dir=calloc(MAXNAME,sizeof(char));
temp=chkdir(argv[1]);
for(i=0;*(temp+i)!='\0';i++)
*(sor_dir+i)=*(temp+i);
*(sor_dir+i)='\0';
temp=chkdir(argv[2]);
for(i=0;*(temp+i)!='\0';i++)
*(des_dir+i)=*(temp+i);
*(des_dir+i)='\0';
printf("$$$$$\n");//测试,奇怪的地方就发生在这里
if((from_dir=opendir(sor_dir))==NULL)
oops(argv[1],argv[2]);
if((to_dir=opendir(des_dir))==NULL)
oops(argv[1],argv[2]);
printf("$$$\n") ;
while((direntp=readdir(from_dir))!=NULL)
{
memset(buf,0x0,BUFFERSIZE);
if((strcmp(direntp->d_name,"..")==0)||(strcmp(direntp->d_name,".")==0))
continue;
filepath=getfpath(direntp->d_name,sor_dir);
printf("Copy file:%s\n",filepath);
if((in_file=open(filepath,O_RDONLY))==-1)
{
perror("\nOpean File Error:");
continue;
}
if((filepath=getfpath(direntp->d_name,des_dir))==NULL)
{
perror("\nChange file path error");
exit(1);
}
else if((out_file=creat(filepath,0666))<0)
{
perror("\nCreat file error:");
exit(1);
}
else if(read(in_file,buf,BUFFERSIZE)==-1)
{
perror("\nRead file error:");
exit(1);
}
else if(write(out_file,buf,sizeof(buf))==-1)
{
printf("%d/n",out_file);
perror("Write file error");
exit(1);
}
}
free(sor_dir);
free(des_dir);
return 0;
}
--------------------------------------------------------
我将部分代码改过了,结果OK! |
|