Jose Ramon
Jose Ramon

Reputation: 5444

How to cut and paste files in c++

I am trying to use rename function to change files locations in c++. My problem is that I want to have as input and output strings and rename it seems to work only with chars. What have to do??

EDIT1:

 for(int i=0; i<dirs.size(); i++){
    if(directories.size()>1)
       for (int k=0; k<= directories.size()/2; k++){
         result = rename((filePath+dirs[i]+directories[k]).c_str(), ("test1/"+dirs[i]+directories[k]).c_str());
       } 
    }
  }

Basically I want to cut and paste the half files of filePath/dir[i] dir to newfilePath/dir[i] dir. newFilePath directory is empty so I want also to create the same dir[i] folders and cut the files into the new path. It seems that rename doesn't create new folders.

EDIT2:

I add mkdir function in order to create the same dir[i] folders in the new directory. However, the rename function doesn't move files in the new directories!!

for(int i=0; i<dirs.size();i++){
        if(directories.size()>1){
          mkdir(dirs[i].c_str(), 0777);
            for (int k=0; k<= directories.size()/2; k++){
                 result= rename( (filePath+dirs[i]+directories[k]).c_str() , ("test1/"+dirs[i]+directories[k]).c_str()  );
             }
         }
 } 

Upvotes: 1

Views: 2146

Answers (3)

Jose Ramon
Jose Ramon

Reputation: 5444

Ok silly me I forgot to add "/" in the path between filepath and dir[i], rename works fine!!

Upvotes: 0

Zhen
Zhen

Reputation: 4283

You should use c_str function to access string as a C null-terminated array:

for( int k=0; k<= directories.size()/2; k++ ){
    std::string oldstr = filePath+dirs[i]+directories[k];
    std::string newstr = "test1/"+dirs[i]+directories[k]; 
    result = rename( oldstr.c_str() , newstr.c_str() );
}

or data function if you are using C++11.

Upvotes: 1

Emanuele Paolini
Emanuele Paolini

Reputation: 10162

Use c_str method of std::string:

for (int k=0; k<= directories.size()/2; k++){
  result = rename((filePath+dirs[i]+directories[k]).c_str(), ("test1/"+dirs[i]+directories[k]).c_str());
}  

Upvotes: 4

Related Questions