File copy function

How do I create a file copy function?

I recently developed a code, but this produces incorrect result, cause some characters are still left in the source file if the number of characters in destination file is less than the number of characters in source file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
void filecopy(FILE *dest, FILE *src)
{
	char ch;
	rewind(src);
	rewind(dest);
	while((ch=fgetc(src)) != EOF)
	{
		fputc(ch, dest);
	}
	fflush(dest);
	rewind(src);
	rewind(dest);
}


Correct this please

Thanks people!!! :-)
EOF may be a valid character in a binary file.
Use while (!feof(src)) instead.
What if, the dest file, already contains something written in it..

Those char stil are left in the dest file after copying.. :(
1
2
3
4
5
6
7
8
#include <fstream>

void copy_file( const char* srce_file, const char* dest_file )
{
    std::ifstream srce( srce_file, std::ios::binary ) ;
    std::ofstream dest( dest_file, std::ios::binary ) ;
    dest << srce.rdbuf() ;
}
SameerThigale wrote:
What if, the dest file, already contains something written in it..

Those char stil are left in the dest file after copying.. :(

You didn't show the code where the file is opened. Depending on the open mode you can discard or keep the previous content.
@JLBorges
Thanks. That solution executes considerably faster, as well as being straightforward.
Another version I've been trying out. The size of the buffer may be system dependent. It can be optimised for faster execution.

1
2
3
4
5
6
7
8
9
10
11
12
13
void filecopy(FILE *dest, FILE *src)
{
    const int size = 16384;
    char buffer[size];

    while (!feof(src))
    {
        int n = fread(buffer, 1, size, src);
        fwrite(buffer, 1, n, dest);
    }

    fflush(dest);
}
Last edited on
I've opened the file using fopen() in the "w+" mode
The '+' implies you want to read from the file as well as write to it. Not sure why you'd want to do that. Also, with that mode specifier the file is opened as text mode.

http://www.cplusplus.com/reference/clibrary/cstdio/fopen/

For a file copy, binary mode is better.

1
2
3
4
5
6
7
8
9
10
void fileopen_and_copy(char * dest, char * src)
{
    FILE * infile  = fopen(src,  "rb");
    FILE * outfile = fopen(dest, "wb");

    filecopy(outfile, infile);

    fclose(infile);
    fclose(outfile);
}

I see on the reference page linked above, "On some library implementations, opening or creating a text file with update mode may treat the stream instead as a binary file."

Perhaps that is the case for your compiler. However, I'd still recommend the use of the 'b' flag for binary mode instead.

One more comment. Your original post included statements for file rewind. But if all you ever do is simply open, copy and close, there is no need for rewind.
Last edited on
Thanks all!! :)

Everything worked :)
Topic archived. No new replies allowed.