Search code examples
cfgetc

fgetc and fputc in C


I am trying to copy 5 bytes from the start of one file and put them into the start of another file. However they are not copying across accurately. I think the problem is in fputc and fgetc, but not sure what...

bmpFile = fopen("frog.bmp", "rb");
encodedFile = fopen("encodedFrog.bmp", "rwb");

for (int i=0; i<5; i++){
    fputc(fgetc(bmpFile), encodedFile); //copy that byte, unchanged into the   output
}

//close and open both files, read the first 5bytes back;
fclose(bmpFile);
fclose(encodedFile);
bmpFile = fopen("frog.bmp", "rb");
encodedFile = fopen("encodedFrog.bmp", "rwb");
for (int i=0; i<5; i++){
    unsigned int actual = fgetc(bmpFile);
    unsigned int value = fgetc(encodedFile);
    printf("actual: %d \tvalue: %d\n", actual, value);
}

The result of this is:

actual: 66  value: 66
actual: 77  value: 77
actual: 54  value: 134
actual: 115     value: 68
actual: 20  value: 17

Thanks


Solution

  • "rwb" is not a valid fopen mode. You probably want to use

    fopen("encodedFrog.bmp", "r+b");
    

    which will open an existing file for input and output in binary mode. If the file does not exist, you should use "w+b".

    fopen("encodedFrog.bmp", "w+b");
    

    This opens a new file for input and output in binary mode.

    Also, as @amdixon mentioned, instead of reopening the files, you should use rewind, which resets the stream position to the beginning.