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);

回答1

读取整个文件,然后将其写入

并且不要使用 (!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');

回答2

分段错误是由指向无效的内存位置引起的。

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

if (destination == NULL || source == NULL)
{
  printf ("Error! Could not open file\n");
  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);

相似文章

随机推荐

最新文章