从cmd和Codeblocks执行时输出不同

Anm*_*ggi 5 c++ boost cmd codeblocks boost-filesystem

从CodeBlocks和cmd执行时,以下程序给出不同的结果 - :

#include <iostream>
#include <string>
#define BOOST_FILESYSTEM_NO_DEPRECATED
#include <boost/filesystem.hpp>

using namespace std;
using namespace boost::filesystem;

int main()
{
    // A valid existing folder path on my system.
    // This is actually the path containing the program's exe.
    path source = "D:\\anmol\\coding\\c++\\boost\\boost1\\bin\\release";

    cout << "output =  " << equivalent( source, "D:" ) << " !!!\n";
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

CodeBlocks从IDE内部运行后的输出 - :

output = 0 !!!
Run Code Online (Sandbox Code Playgroud)

通过boost1在将当前目录更改为包含可执行文件的文件夹(source代码中提到的路径)后执行cmd的输出- :

output = 1 !!!
Run Code Online (Sandbox Code Playgroud)

据我所知,CodeBlocks给出的输出应该是正确的.

我在Windows 7 SP1 64位和CodeBlocks 13.12上运行此程序.
我使用TDM-GCC 4.9.2(32位)和Boost 1.57来构建这个程序.

只有在将当前目录更改为包含可执行文件的文件夹后执行程序时,才会出现cmd的错误输出.
如果我将cmd的当前目录保存到其他文件夹,则会显示正确的输出.

编辑 - :

我试图解决的原始问题是检查文件/目录是否是另一个目录的后代.
为了实现这一点,我实现了以下代码 - :

#include <iostream>
#include <string>
#define BOOST_FILESYSTEM_NO_DEPRECATED
#include <boost/filesystem.hpp>

using namespace std;
using namespace boost::filesystem;

// Returns the difference in height in the filesystem tree, between the directory "parent" and the file/folder "descendant"
static int HeightDiff( const path parent, path descendant )
{
    int diff = 0;
    while ( !equivalent( descendant, parent ) )
    {
        descendant = descendant.parent_path();
        if ( descendant.empty() )
        {
            diff = -1;  // "descendant" is not a descendant of "parent"
            break;
        }
        diff++;
    }
    return diff;
}

// Returns true if the file/folder "descendant" is a descendant of the directory "parent"
static bool IsDescendant( const path parent, path descendant )
{
    return HeightDiff( parent, descendant ) >= 1;
}

int main( int argc, char** argv )
{
    if ( isDescendant( canonical( argv[1] ), canonical( argv[2] ) ) )
    {
        cerr << "The destination path cannot be a descendant of the source path!! Please provide an alternate destination path !!" << endl;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,如果我用argv[1]="D:\anmol\coding\c++\boost\boost1\bin\release"和执行代码argv[2]="D:\anmol\coding\c++\boost\boost1\bin",它将返回true,而它应该返回false.(因为,在这种情况下,parent实际上是其后代descendant)

这样做的原因是,在while循环中HeightDiff(),在一些迭代之后,descendant将获取该值D:.因此,equivalent()将返回true并在循环之前停止循环descendant变为空字符串.

我之前不知道D:那是指当前目录,因此问了这个问题.

有没有办法修改HeightDiff功能,以便提供正确的输出?

在所有情况下都会更换equivalent()条件并while(descendant != parent)给出正确的输出吗?

如果没有,那么还有其他解决方案吗?

Anm*_*ggi 2

equivalent条件替换为 后while(descendant != parent),程序运行正常。