remmstein 2015-06-12 03:08 采纳率: 0%
浏览 1861

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

  • 写回答

5条回答

  • remmstein 2015-06-12 03:15
    关注

    #include
    #include
    #include
    #include
    #include
    #include
    #include这是上面的库函数

    评论

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀