Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing appropriate data types (path, string, etc.) with boost::filesystem in C++ to efficiently iterate files, change filenames, and do file operations
    primarykey
    data
    text
    <p>The following code loops through files in "sourcepath" and copies them to "destpath". If they exist, they are renamed as "Copy of" the original filename.</p> <p>Do I really need this much code for this? I get the feeling I'm doing way too much back-and-forth converting between strings and paths, but I'm not sure how else to do it.</p> <p>Is there a less complicated and more efficient way to do this, or is this as good as it gets?</p> <p>System: Win32(XP), Boost libraries: 1.44 v2, Dev env: Visual Studio TS 2008</p> <pre><code>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-&gt;filename()); std::string strDestFilename(pathDest.string() + "/" + iterDir-&gt;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-&gt;filename()); bfs::path pathNewDestFilename(strNewDestFilename); bfs::copy_file(pathSourceFilename, pathNewDestFilename); } } </code></pre> <p><strong>ETA: Moved "Copy of" to the right place (next to the filename rather than the dir name).</strong></p> <p><strong>ETA2: Refactored using suggested edits:</strong></p> <pre><code>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-&gt;filename()); bfs::path pathDestFilename(pathDest / iterDir-&gt;filename()); if(!bfs::exists(pathDestFilename)) bfs::copy_file(pathSourceFilename, pathDestFilename); else { std::string strNewDestFilename("Copy of " + iterDir-&gt;filename()); bfs::path pathNewDestFilename(pathDest / strNewDestFilename); bfs::copy_file(pathSourceFilename, pathNewDestFilename); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload