从 cmd 和代码块执行时输出不同

Different output when executing from cmd and Codeblocks

本文关键字:输出 执行 cmd 代码      更新时间:2023-10-16

以下程序在从 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;
}

从 IDE 内部运行代码块后的输出 -:

output = 0 !!!

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

output = 1 !!!

据我说,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;
    }
}

现在,如果我使用 argv[1]="D:anmolcodingc++boostboost1binrelease"argv[2]="D:anmolcodingc++boostboost1bin" 执行代码,它将返回 true ,而它应该返回 false 代替。(因为在这种情况下,parent实际上是descendant的后代)

原因是在 HeightDiff() 的 while 循环中,经过一些迭代,descendant 会将值取D:。因此,equivalent()将返回 true 并在循环变为空字符串之前一步停止循环descendant

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

有没有办法修改HeightDiff函数,以便它给出正确的输出?

equivalent()条件替换为while(descendant != parent)在所有情况下都能提供正确的输出吗?

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

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

只需替换

equivalent( source, "D:" )

equivalent( source, "D:\" )

你应该得到预期的结果:D:后面的斜杠(如Serge Rogatch所建议的)将使字符串引用根目录。