#include
#include
#include
#include
#include
#include
#include
#define BUFSIZE 4096
#define COPYMODE 0644
void oops(char *,char *);
void *emalloc(size_t);
void do_copy(char *,char *);
void copydir(char *,char *);
int isdir(char *);
int main(int ac,char *av[])
{
if(ac != 3){
fprintf(stderr,"juast fun");
exit(1);
}
if(isdir(av[1])){
if(isdir(av[2]))
copydir(av[1],av[2]);
else{
fprintf(stderr,"file:isnotadirectory%s\n",av[2]);
exit(1);
}
}
else
do_copy(av[1],av[2]);
return 0;
}
void copydir(char *src,char *dst)
{
char *srcfile,*dstfile;
srcfile=(char *)emalloc(sizeof(src)+1+MAXNAMLEN+1);
dstfile=(char *)emalloc(sizeof(dst) +1+ MAXNAMLEN+1);
DIR *dir_ptr;
struct dirent *direntptr;
if((dir_ptr=opendir(src))==NULL)
oops("can'topendir",src);
while((direntptr=readdir(dir_ptr))!=NULL){
sprintf(srcfile,"%s/%s",src,direntptr->d_name);
if(isdir(srcfile)){
if(strcmp(direntptr->d_name,".") != 0 &&
strcmp(direntptr->d_name,"..")!= 0)
printf("%s is adirectorythatpassed",srcfile);
continue;
}
sprintf(dstfile,"%s/%s",dst,direntptr->d_name);
do_copy(srcfile,dstfile);
}closedir(dir_ptr);
free(srcfile);
free(dstfile);
}
void do_copy(char *file,char *dir)
{
int in_fn,out_fn,n;
char m[BUFSIZE];
char *dirname;
char *dirnamed(char *,char *);
dirname = dirnamed(file,dir);
if((in_fn = open(file,O_RDONLY))==-1)
oops("can'topen",file);
if((out_fn = creat(dirname,COPYMODE))==-1)
oops("can'tcreat",dir);
while((n = read(in_fn,m,BUFSIZE))>0)
if(write(out_fn,m,n) != n)
oops("can,t write",dirname);
if(n == -1)
oops("readerrorfrom",file);
if(close(in_fn)==-1||close(out_fn)==-1)
oops("can'tclose","");
}
void oops(char *s1,char *s2)
{
fprintf(stderr,"ERROR: %s",s1);
perror(s2);
exit(1);
}
char *dirnamed(char *file,char *dir)
{
struct stat info;
char *scrfile=NULL;
char *rv;
if(stat(dir,&info)==-1)
return dir;
if(!S_ISDIR(info.st_mode))
return dir;
if((scrfile = strrchr(file,'/'))!= NULL)
scrfile++;
else
scrfile = file;
rv = emalloc(strlen(scrfile)+2+strlen(dir));
sprintf(rv,"%s/%s",dir,scrfile);
return rv;
}
int isdir(char *name)
{
struct stat info;
return (stat(name,&info)!=-1 && S_ISDIR(info.st_mode));
}
void *emalloc(size_t n)
{
void *p;
p = malloc(n);
if(p = NULL)
oops("out of memory","");
return p;
}
这个编译时没问题,使用时argv[1]是文件,就弹出out of memory,文件夹就弹出segement..,是stack的问题吗
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。