简体   繁体   English

Boost rename()函数不起作用

[英]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 我正在使用Windows 7,CodeBlocks 10.05,G ++ 4.4.1和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. 第二种情况测试move函数是否存在,即它的指针不是NULL(总是为真),第一种情况测试移动是否成功。

  • Avoiding c-style casts helps in avoiding many problems like accidentally doing if(void) 避免使用c风格的演员表有助于避免许多问题,比如意外做if(void)
  • implicit concatenation of strings "C:\\\\fldr1" "rawr.txt" == "C:\\\\fldr1rawr.txt" also may produce undesired results. 字符串"C:\\\\fldr1" "rawr.txt" == "C:\\\\fldr1rawr.txt"隐式串联也可能产生不希望的结果。
  • 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. 在这里,您正在测试函数指针不为null - 您需要实际调用该函数。 Try 尝试

if(move())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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