Read and copy file with EOF indicator in the middle

非 Y 不嫁゛ 提交于 2019-12-11 15:46:06

问题


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


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/3866075/read-and-copy-file-with-eof-indicator-in-the-middle

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!