Using appropriate data types (path, string, etc.) With boost :: filesystem in C ++ to efficiently iterate files, change file names and perform file operations

The following code iterates over the files in the "sourcepath" and copies them to the "destpath". If they exist, they are renamed as "Copy" of the original file name.

Do I really need this code for this? It feels like I'm doing too many transitions between lines and tracks, but I'm not sure how to do this.

Is there a less complex and efficient way to do this, or is it as good as it gets?

System: Win32 (XP), Boost libraries: 1.44 v2, Dev env: Visual Studio TS 2008

namespace bfs = boost::filesystem;

bfs::path pathSource("C:/dir/sourcepath");
bfs::path pathDest("C:/dir/destpath");

for (bfs::directory_iterator iterDir(pathSource); 
    iterDir!=bfs::directory_iterator(); iterDir++)
{
    std::string strSourceFilename(pathSource.string() + "/" 
        + iterDir->filename());
    std::string strDestFilename(pathDest.string() + "/" 
        + iterDir->filename());
    bfs::path pathSourceFilename(strSourceFilename);
    bfs::path pathDestFilename(strDestFilename);

    if(!bfs::exists(pathDestFilename))
        bfs::copy_file(pathSourceFilename, pathDestFilename);
    else {
        std::string strNewDestFilename(pathDest.string() 
            + "/" + "Copy of " + iterDir->filename());
        bfs::path pathNewDestFilename(strNewDestFilename);
        bfs::copy_file(pathSourceFilename, pathNewDestFilename);
    }
}

ETA: Moved "Copy" to the desired location (next to the file name, not the dir name).

ETA2: :

namespace bfs = boost::filesystem;

bfs::path pathSource("C:/dir/sourcepath");
bfs::path pathDest("C:/dir/destpath");

for (bfs::directory_iterator iterDir(pathSource); 
    iterDir!=bfs::directory_iterator(); iterDir++)
{
    bfs::path pathSourceFilename(pathSource / iterDir->filename());
    bfs::path pathDestFilename(pathDest / iterDir->filename());

    if(!bfs::exists(pathDestFilename))
        bfs::copy_file(pathSourceFilename, pathDestFilename);
    else {
        std::string strNewDestFilename("Copy of " + iterDir->filename());
        bfs::path pathNewDestFilename(pathDest / strNewDestFilename);
        bfs::copy_file(pathSourceFilename, pathNewDestFilename);
    }
}
+3
1

path /, .

std::string strSourceFilename(pathSource.string() + "/" 
    + iterDir->filename());
std::string strDestFilename(pathDest.string() + "/" 
    + iterDir->filename());
bfs::path pathSourceFilename(strSourceFilename);
bfs::path pathDestFilename(strDestFilename);

bfs::path pathSourceFilename(pathSource / iterDir->filename());
bfs::path pathDestFilename(pathDest / iterDir->filename());

( pathNewDestFilename).

+4

Source: https://habr.com/ru/post/1776805/


All Articles