代码不起作用,得到错误:分段错误(核心转储)

时间:2014-06-09 08:45:16

标签: c

有人可以解释为什么这段代码不起作用? 它打算复制一个文件,当我编译它时我得到分段错误(核心转储),我感谢所有批评者。对不起,如果有任何拼写错误。

#include <stdio.h>
#include <stdlib.h>

#define BUFSIZE 256
#define MAXLEN 30

void copy(FILE *source,FILE *dest);    

int main(void)
{
       FILE *fs, *fa;                              // fs for source file, fa for copy

       char file_src[MAXLEN];                      // name of source file
       char file_app[MAXLEN];                      // name of copy file

       puts("File copy program\n\n");
       puts("Enter name of source file:");
       gets(file_src);                             // get the file name
       if(fs=fopen(file_src,"r")==NULL)           // error checking
       {
             fprintf(stderr,"Cant open %s.\n",file_src);
             exit(EXIT_FAILURE);
       }
       if(setvbuf(fs,NULL,_IOFBF,BUFSIZE)!=0)   //  set the buffer for fs
        {
             fprintf(stderr,"Cant create input buffer.\n");
             exit(EXIT_FAILURE);
       }
       puts("Now enter the copy name file:");
       gets(file_app);                             // get file name

       if(fa=fopen(file_app,"w")==NULL)            // error checking
       {
             fprintf(stderr,"Cant open %s.\n",file_app);
             exit(EXIT_FAILURE);
       }
       if(setvbuf(fa,NULL,_IOFBF,BUFSIZE)!=0)      // set up buffer for fa
       {
             fprintf(stderr,"Cant create output buffer.\n");
             exit(EXIT_FAILURE);
       }
       copy(fs,fa);                              // copy file fs to fa

       if(ferror(fs)!=0)
       {
             fprintf(stderr,"Error in reading file\n");
             exit(EXIT_FAILURE);
       }
       if(ferror(fa)!=0)
       {
             fprintf(stderr,"Error in writing file\n");
             exit(EXIT_FAILURE);
       }
       puts("Done");
       return 0;
}

void copy(FILE *source,FILE *dest)
{
       size_t bytes=0; 
       static char temp[BUFSIZE];

       while(bytes=fread(temp,sizeof(char),BUFSIZE,source) > 0)   
            fwrite(temp,sizeof(char),bytes,dest);
}

1 个答案:

答案 0 :(得分:5)

此:

if(fs=fopen(file_src,"r")==NULL)

错了。当打开成功时,可能最终将fs分配给NULL,然后检查,从而导致{ {1}}用于以后的调用。

一定是

NULL

由于操作员优先级如何在C中起作用。

顺便说一下,像这样的通用复制程序应该以二进制模式打开文件。