Boost rename()函数不起作用

Run*_*oid 2 c++ boost g++ codeblocks

编译器在构建时没有抱怨,我的程序说它有效,并创建了文件夹,但文件没有移动.我究竟做错了什么?

#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;
}
Run Code Online (Sandbox Code Playgroud)

我正在使用Windows 7,CodeBlocks 10.05,G ++ 4.4.1和Boost 1.47

Kar*_*nek 7

我想你的意思

if (move()){
Run Code Online (Sandbox Code Playgroud)

代替

if (move){
Run Code Online (Sandbox Code Playgroud)

第二种情况测试move函数是否存在,即它的指针不是NULL(总是为真),第一种情况测试移动是否成功.


AJG*_*G85 5

  • 避免使用c样式强制转换有助于避免许多问题,例如意外执行 if(void)
  • 字符串的隐式串联"C:\\fldr1" "rawr.txt" == "C:\\fldr1rawr.txt"也可能会产生不希望的结果。
  • Boost重命名会引发您未处理的异常。
  • 依靠文字字符串的隐式转换来提升路径是一个较小的问题。

您可以改为执行以下操作:

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

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

  return exists(dest);
}
Run Code Online (Sandbox Code Playgroud)