有人可以解释为什么这段代码不起作用?它打算复制一个文件,当我编译它时我得到分段错误(核心转储),我感谢所有批评者.对不起,如果有任何错别字.
#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);
}
Run Code Online (Sandbox Code Playgroud)
这个:
if(fs=fopen(file_src,"r")==NULL)
Run Code Online (Sandbox Code Playgroud)
是错的.它可能最终分配fs给NULL,当打开 成功时,然后不检查,因此NULL在以后的调用中使用时会导致错误.
肯定是
if((fs = fopen(file_src, "r")) == NULL)
Run Code Online (Sandbox Code Playgroud)
由于运营商优先级如何在C中工作
顺便说一句,像这样的通用复制程序应该以二进制模式打开文件.