I want to write a Code in C which can create copy any given file (txt, bmp, jpg, pdf etc) what i've written so far is:

int main(){

    FILE *fp;
    char ch;
    FILE *fpW;

    if((fpW = fopen("file2.bmp","w"))==NULL) {
        printf("Cannot open Destination file.\n");
        exit(1);
    }

    if((fp = fopen("file.bmp","r"))==NULL) {
        printf("Cannot open Source file.\n");
        exit(1);
    }

    while((ch = fgetc( fp )) != EOF) {
        fputc(ch, fpW);
    }

    fclose(fp);
    fclose(fpW);    
    //printf("\n %s \n",ret);

    return 0;
}

it works fine with txt file but doesn't work with pdf and image files .... please Help ..!!

Edited 3 Years Ago by Reverend Jim: Fixed formatting

Open files in binary mode.

you mean i only need to replace if((fp = fopen("file.bmp","r"))==NULL) with if((fp = fopen("file.bmp","rb"))==NULL)
and remaining code will remain the same as i've posted above ????

Now i've changed my code to:

int main(){


    FILE *fp;
    char ch;
    FILE *fpW;


    if((fpW = fopen("file2.gif","wb"))==NULL) {
        printf("Cannot open Destination file.\n");
        exit(1);
    }

    if((fp = fopen("file.gif","rb"))==NULL) {
        printf("Cannot open Source file.\n");
        exit(1);
    }

    while((ch = fgetc( fp )) != EOF) {

        fputc(ch, fpW);
    }

    fclose(fp);
    fclose(fpW);    
    //printf("\n %s \n",ret);

    return 0;
}

but it still isn't working ... plz help :(

Edited 3 Years Ago by Nick Evan: Fixed formatting

ch should be an int.

[edit]Using code tags helps get/keep my attention.

But i want to print char by char ... wat's the logic to take it int ???

Plz explain ... and tell me, if possible, how should i change my code???

This article has been dead for over six months. Start a new discussion instead.