How to copy a file in C++

Started by
11 comments, last by ontheheap 17 years, 10 months ago
How could I copy a file from a folder to another one and replace the file if it already exists ? cheers !!
Advertisement
The easy way is to use an operating system specific function like CopyFile() in the Windows API.

Using file streams you can open the source file with an ifstream, then the destination file with an ofstream and stream the input stream's rdbuf into the ofstream.
Quote:Original post by SiCrane
The easy way is to use an operating system specific function like CopyFile() in the Windows API.

Using file streams you can open the source file with an ifstream, then the destination file with an ofstream and stream the input stream's rdbuf into the ofstream.


ah ah ah. i'm more confused than before...
You can also use the system command in windows and use batch/dos programming to copy the file, like this:

system("copy file1.exe folder");

Using Win API functions may be better though, but this is a way to do it under windows that also works.
Because I'm feeling particularly generous ... this is some code I've recently written for one of my own programs. Feel free to alter it for your own purposes (I'm fairly certain this will replace a file if it already exists, but if you find that it doesn't, just look up the remove() function, implement it, and you should be good to go.
#include <fstream>#include <string>#include <stdio.h>#include <iostream>using namespace std;//CopyFile is a simple function that copies a file from arg1 to arg2int CopyFile(string initialFilePath, string outputFilePath){		ifstream initialFile(initialFilePath.c_str(), ios::in|ios::binary);	ofstream outputFile(outputFilePath.c_str(), ios::out|ios::binary);	//defines the size of the buffer	initialFile.seekg(0, ios::end);	long fileSize = initialFile.tellg();	//Requests the buffer of the predefined size	//As long as both the input and output files are open...	if(initialFile.is_open() && outputFile.is_open())	{		short * buffer = new short[fileSize/2];		//Determine the file's size		//Then starts from the beginning		initialFile.seekg(0, ios::beg);		//Then read enough of the file to fill the buffer		initialFile.read((char*)buffer, fileSize);		//And then write out all that was read		outputFile.write((char*)buffer, fileSize);		delete[] buffer;	}	//If there were any problems with the copying process, let the user know	else if(!outputFile.is_open())	{		cout<<"I couldn't open "<<outputFilePath<<" for copying!\n";		return 0;	}	else if(!initialFile.is_open())	{		cout<<"I couldn't open "<<initialFilePath<<" for copying!\n";		return 0;	}			initialFile.close();	outputFile.close();	return 1;}


Note, this code *should* work for any platform... if it doesn't, let me know. I haven't actually tested it on other platforms.
Also, be aware that this code will use up an amount of memory equal to the size of the file you're copying. I'd suggest altering the sourcecode to write out the file in smaller chunks if you plan to deal with files larger than half of your available RAM.
I'd very much like to see if anyone has any more efficient but non-platform-specific code, though!
Quote:Original post by SiCrane
Using file streams you can open the source file with an ifstream, then the destination file with an ofstream and stream the input stream's rdbuf into the ofstream.


That sounds almost dirty, doesn't it?

Quote:Original post by jolyqr
ah ah ah. i'm more confused than before...


std::ifstream ifs("input.txt", std::ios::binary);std::ofstream ofs("output.txt", std::ios::binary);ofs << ifs.rdbuf();
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
Simply stating that you are confused is not a useful response. Do you not know how to call an operating specific function? Do you not know what operating system you are using? Do you not know what an operating system is? Do you not know what a function is? Do you not know what an ifstream is? Do you not know what an ofstream is? Do you not understand how to stream an rdbuf? When all you say is that you are confused, it leaves no indication how to help you become unconfused.
Here's how I would do it, a pretty simple way(this is more of the c way of doing it, but still works in c++):

#include <stdio.h>#include <stdlib.h>int main(int argc,char *argv[]){  int c;  FILE *in,*out;  if(argc != 3)  {     printf("Usage: copy <source> <dest>\n");  }  else   {     in = fopen( argv[1], "r" );     out = fopen( argv[2], "w" );     if(in==NULL || !in)     {	fprintf(stderr,"%s: No such file or directory\n",argv[1]);	return 0;     }     else if(out==NULL || !out)     {	fprintf(stderr,"%s: No such file or directory\n",argv[2]);	return 0;     }     while((c=getc(in))!=EOF)       putc(c,out);      fclose(in);      fclose(out);  }  return 0;}

This should be non-platform specific.

You could also use getline to get each line and then fprintf(out, "%s", line) to print line by line instead of char by char, but would essentially be the same thing.

EDIT: a little late :( , darn my crappy dialup

[Edited by - glaeken on June 21, 2006 12:52:12 PM]
Quote:Original post by Fruny


std::ifstream ifs("input.txt", std::ios::binary);std::ofstream ofs("output.txt", std::ios::binary);ofs << ifs.rdbuf();


^ That's a winner.


cheers everybody, i'm going to use the CopyFile() of Windows API.

This topic is closed to new replies.

Advertisement