[英]Code doesn't work, getting error: segmentation fault(core dumped)
有人可以解釋為什么這段代碼不起作用嗎? 它旨在復制文件,當我編譯它時遇到分段錯誤(核心轉儲),我感謝所有批評家。 抱歉,有錯別字。
#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);
}
這個:
if(fs=fopen(file_src,"r")==NULL)
是錯的。 當打開成功時 ,可能最終將fs
分配給NULL
,然后不對其進行檢查,從而在以后的調用中使用NULL
時導致錯誤。
一定是
if((fs = fopen(file_src, "r")) == NULL)
由於操作員優先級在C中的工作方式。
順便說一句,像這樣的通用復制程序應該以二進制模式打開文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.