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 ..!!

Recommended Answers

All 6 Replies

Open files in binary mode.

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 :(

ch should be an int.

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

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???

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

Correctness?
http://web.archive.org/web/20050207005628/http://dev.unicals.com/papers/c89-draft.html#4.9.7.1

int fgetc(FILE *stream);

http://web.archive.org/web/20050207005628/http://dev.unicals.com/papers/c89-draft.html#4.9.7.3

int fputc(int c, FILE *stream);

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

ch should be an int.

Open files in binary mode.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.