Search code examples
c++file-copyingpathname

Add a variable as pathname to CopyFile command in C++


I have been searching but don't seem to be able to correct way to replace the path in a CopyFile command by a variable that stores the path.

The idea is to copy a file and rename it with a different number to a certain directory. I managed to get the code working with fixed pathname and filename. But i need to copy this 1000 times with each time a different number. Hope someone can tell me how to incorporate the variable in the copyfile command.

#include <iostream>
#include <fstream>
#include <windows.h>
#include <string>
#include <sstream>

using namespace std;
int main()
{


    int a=6;
    string name = "Slide";
    string newname;
    string directory = "d:/--- STEPHANE FILES ---/powerpoint/";
    string destination;

    ostringstream oss;
    oss << name << a ;
    newname = oss.str();


    ostringstream oss1;
    oss1 << directory << newname << ".JPG";
    destination = oss1.str();

    cout << destination;


    CopyFile("d:/--- STEPHANE FILES ---/powerpoint/Slide1.jpg", destination, TRUE);


    return 0;
}

Solution

  • Since it appears that you are using the ANSI version you can pass in the c._str() member function to CopyFile:

    CopyFile(directory.c_str(), destination.c_str(), TRUE);
    

    Make sure both strings represent the actual path / file name.