Skip to main content
GameDev.net gamedev.net
🔒 Locked

How to copy a file in C++

Started by jolyqr Jun 21, 2006 at 10:47 AM 11 replies 91.9k views
Original Post
jolyqr
jolyqr
How could I copy a file from a folder to another one and replace the file if it already exists ? cheers !!
SiCrane
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.
jolyqr
jolyqr
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...
password
password
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.
twystidmynd
twystidmynd
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!
Fruny
Fruny
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
SiCrane
SiCrane
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.
glaeken
glaeken
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]
twystidmynd
twystidmynd
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.


jolyqr
jolyqr
cheers everybody, i'm going to use the CopyFile() of Windows API.
ontheheap
ontheheap
Above post was mine. I'm using my wife's computer so my info wasn't filled in the fields automagically. Anyways, I was trying to link to Boost Filesystem. Here is a good page to get you started.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.