PDA

View Full Version : Copying a file


shivam
12-22-03, 01:08 AM
Hi every body how are you? I'm trying to write a program in C++ that does the following: scans a folder for files, selects one of these files at random, copies the selected file to a prespecified folder, then renames this file to a another predifined name. So far I've the part that scans the folder selects a random file, I need help in copying this selected file to a another folder. Can any one please help? It will be greatly appreciated.
So far I have the following code:

#include<windows.h>
#include<stdlib.h>
#include<time.h>
#include<iostream>
using namespace std;
int main()
{
srand(time(0));
WIN32_FIND_DATA buf;
HANDLE find=FindFirstFile("*.txt",&buf);
if(find==INVALID_HANDLE_VALUE)
{
cout<<"No *.txt file"<<endl;
system("pause");
return 0;
}
char*file_found=buf.cFileName;
do
{
if(rand()%3==0)//1 case out of 3
{
file_found=buf.cFileName;
break;
}
}
while(FindNextFile(find,&buf));
FindClose(find);
cout<<"I selected "<<file_found<<endl;
system("pause");
return 0;
}

hyjacked
12-22-03, 07:39 AM
if it's just text files the following will work:
http://www.cs.indiana.edu/classes/h212-lake/streams/streams.html

if you might be copying binary files also, you might want to look into making the copy a system call. From googling around a bit all I could really find was someone suggesting to another with the same problem was to do this.

shivam
12-22-03, 03:14 PM
I solved the problem with the following line of code:

CopyFile("source.file", "destination.file", false);

...where true or fals stands for don't/do overwrite.

fjolnir
07-20-05, 04:52 PM
Here is a link (msdn) that should give a little more detail on 'CopyFile':

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/fileio/fs/copyfile.asp

Enjoy!