简体   繁体   中英

Boost rename() function doesn't work

The compiler doesn't complain while building,and my program says it worked, and creates the folder, but the file hasn't moved. What am I doing wrong?

#include <iostream>
#include <boost/filesystem.hpp>

using namespace std;
using namespace boost::filesystem;

char c = 'c';

bool move(){

 if ((bool) rename("C:\\fldr1" "rawr.txt", "C:\\fldr2" "rared.txt") == (true)){
    return true;
 }
 else{
    return false;
 }

}
int main(int argc, char argv[])
{

    if (argv[1] = (c))
    {
        if (is_directory("C:\\fldr2")){

            if (move){
            cout << "Done 1!" << endl;
            }
        }
        else{
            cout << "Dir doesn't exist!" << endl;

            if ((bool)create_directory("C:\\fldr2") == (true)){

                if (move){
                    cout << "Done 2!" << endl;
                }
            }
        }
    }
    return 0;
}

I'm using Windows 7, CodeBlocks 10.05, G++ 4.4.1, and Boost 1.47

I think you meant

if (move()){

instead of

if (move){

The second case tests if the move function exists, ie its pointer is not NULL (which is always true), the first case tests if the move succeeded.

  • Avoiding c-style casts helps in avoiding many problems like accidentally doing if(void)
  • implicit concatenation of strings "C:\\\\fldr1" "rawr.txt" == "C:\\\\fldr1rawr.txt" also may produce undesired results.
  • Boost rename can throw exceptions which you aren't handling either.
  • Relying on implicit casting of literal string to boost path is a lesser problem.

You could do something like the following instead:

bool move()
{
  path src("C:\\fldr1\\rawr.txt");
  path dest("C:\\fldr2\\rared.txt");

  try {
    rename(src, dest);
  }
  catch (...)
  {
    return false;
  }

  return exists(dest);
}
 if (move)

Here you are testing that the function pointer is not null - you need to actually call the function. Try

if(move())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM