开发者社区> 问答> 正文

c语言在linux环境下进行文件复制的代码,使用时出错,求各位大神帮忙解答下

#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的问题吗

展开
收起
杨冬芳 2016-07-11 18:53:27 2643 0
1 条回答
写回答
取消 提交回答
  • IT从业

    void *emalloc函数里面写错了吧

    if ( p = NULL ) //应该是等于号吧

    2019-07-17 19:54:37
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
Alibaba Cloud Linux 3 发布 立即下载
ECS系统指南之Linux系统诊断 立即下载
ECS运维指南 之 Linux系统诊断 立即下载