C文件复制错误

  • 本文关键字:错误 复制 文件 c
  • 更新时间 :
  • 英文 :


我正在尝试将文件内容从源复制到目标。我的代码遇到了分段错误(在打开目标文件之后)。如果您能帮忙调试这个问题,我将不胜感激。

FILE* source = fopen(fname, "r");
char_u* ver2_fname = str_replace(fname, "version1", "version2");
FILE* destination = fopen(ver2_fname, "w");
free(ver2_fname);
// transfer ver2_file_read from version 1 to version 2
char character;
while (!feof(source))
{
character = fgetc(source);
fputc(character, destination);
}
fclose(source);
fclose(destination);

读取整个文件然后写入
并且不要使用(!feof(source))而使用ch != EOF

void copy_file_to(const char *src, const char *dest){

char *__dest = NULL;

FILE *file_ = fopen(src,"rb+");
if(file_ == NULL){
fprintf(stderr,"[ERROR]: UnKnown file [%s:%i] n" ,__func__,__LINE__);
exit(-1);
}

fseek(file_,0,SEEK_END);
size_t file_size = ftell(file_);
assert(file_size > 0);
fseek(file_,0,SEEK_SET);
__dest =  malloc((file_size) *sizeof(char));

fread(__dest,1,file_size,file_);

FILE *fpdest = fopen(dest,"wb+");
fwrite(__dest, 1,file_size , fpdest);
fclose(fpdest);
fclose(file_);
free(__dest);
}

或者简单地读成这样:

FILE *fp = fopen("./test.txt", "r+");
int c= fgetc(fp);
while (c != EOF) { 
putchar(c); 
c =fgetc(fp);
}
putchar('n');

分段错误指向无效内存位置。

因此,请检查文件名,并且您有权限在运行代码的上下文中读取内存中的文件。通过在while循环之前添加以下代码片段来检查:

if (destination == NULL || source == NULL)
{
printf ("Error! Could not open filen");
exit (-1);        // must include stdlib.h 
}

除此之外,当使用feof(source)时,它正在选择当前文件指针位置,并且根据代码,它将选择EOF也作为一个字符。

因此使用下面的代码片段:

do
{
// Taking input single character at a time
char c = fgetc(source);
// Checking for end of file
if (feof(source))
break ;
fputc (c, destination);
printf("%c", c);
}  while(1);

最新更新