C++ file copying function problem

chibicitiberiu

New Member
Here is the source code:
Code:
int copyfile(char* source, char* dest)
{
        ifstream input(source, ios::in|ios::binary);
        ofstream output(dest, ios::out|ios::binary);

        if (!input) return -1;
        if (!output) return -2;

        char* a;

        while(!input.eof()) {
                input.read(a, 1);
                output.write(a, 1);
                }


        input.close();
        output.close();

        return 0;

}
What it should do is copy a file, but the problem I get is that the copied file has 1 byte more than the source one. In files like mp3s or others this error didn't matter at all, but in .txt files it does. How can I fix it?

Earlier I tried increasing the amount of data stored in the a variable, but it just increased the difference between the original and copied file.
 
I know this seems odd but eof gets flagged based on the last i/o operation so you end up writing the bad variable out on the last write.

Code:
int copyfile(char* source, char* dest)
{
        ifstream input(source, ios::in|ios::binary);
        ofstream output(dest, ios::out|ios::binary);

        if (!input) return -1;
        if (!output) return -2;

        char* a;

        input.read(a, 1);
        while(!input.eof()) {
                output.write(a, 1);
                input.read(a, 1);
        }


        input.close();
        output.close();

        return 0;

}
 
I know this seems odd but eof gets flagged based on the last i/o operation so you end up writing the bad variable out on the last write.

Code:
int copyfile(char* source, char* dest)
{
        ifstream input(source, ios::in|ios::binary);
        ofstream output(dest, ios::out|ios::binary);

        if (!input) return -1;
        if (!output) return -2;

        char* a;

        input.read(a, 1);
        while(!input.eof()) {
                output.write(a, 1);
                input.read(a, 1);
        }


        input.close();
        output.close();

        return 0;

}

Thanks very much, that fixed the problem.
 
Back
Top