Question

I used the code below to copy from one binary file to another, but the first file contains some EOF indicators (0xFF) as part of it, so the copy function actually copies the file until its first EOF indicator.

For example: if my file is {0x01, 0x02, 0x03, 0xFF, 0x01, 0x02, 0xFF, 0xFF} then only {0x01, 0x02, 0x03} will be copied to the new file. Any idea how to fix it (or maybe I'm missing something there...)

Code:

int Util_Copy_File(char* source, char* dest)
{
    FILE *fs,*ft;  
    char ch;
    char infile[100];
    sprintf(infile, "%s", dest);
    fs = fopen(infile,"r");  
    if(fs==NULL)  
    {
        return -1;  
    }
    ft = fopen(dest,"w");  
    if(ft==NULL)  
    {  
    fclose(fs);  
    return STATUS_FAIL;
    }  

    while(1)  
    {  
    ch = getc(fs);  
    if(ch==EOF)  
    {  
        break;  
    }  
    else  
        putc(ch,ft);  
    } 
    fclose(fs);  
    fclose(ft);
    return 0;
}

Thanks, Binyamin

Was it helpful?

Solution

fgetc returns an int, not a char , so you can tell the difference between EOF and a char with the same value as EOF.

Change:

char ch;

to

int ch

And (usually not relevant if you're on *nix)

fs = fopen(infile,"r");  

to

fs = fopen(infile,"rb");  

OTHER TIPS

0xFF is not EOF. -1 is EOF. The problem is that you're storing the int return value of getc in a char, which collapses 0xFF onto -1 (actually it's implementation-defined behavior but that's what common implementations will do).

The return value of getc is an int whose value is either in the range of unsigned char or EOF (which has value -1). And the correct type for binary data is unsigned char, not char.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top