Home > Software engineering >  C file copying bug
C file copying bug

Time:05-19

I am trying to copy a files contents from source to destination. My code runs into a segmentation fault (after the destination file is opened). I would appreciate help debugging this issue.

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

CodePudding user response:

read the whole file and then write it
and don't use (!feof(source)) instead use 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);
}

or simply read like this:

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

CodePudding user response:

Segmentation Fault is caused by pointing to invalid memory location.

Hence please check the file name and you have permission for the memory to read the file in the context that you ae running the code. Check this by adding the following snippet just before the while loop:

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

Apart from this when using feof(source) it is selecting the current file pointer location and as per the code it will select EOF also as a char.

Hence use following snippet :

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);
  •  Tags:  
  • c
  • Related