以下程序在从CodeBlocks和cmd中执行时会产生不同的结果:
在IDE中运行CodeBlocks后的输出结果为:
据我所知,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;
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中运行CodeBlocks后的输出结果为:
output = 0 !!!
将当前目录更改为包含可执行文件的文件夹(代码中提到的source
路径),并执行boost1
后从cmd输出 -:
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:\anmol\coding\c++\boost\boost1\bin\release"
和argv[2]="D:\anmol\coding\c++\boost\boost1\bin"
执行代码,它将返回true
,但实际上应该返回false
。(因为在这种情况下,parent
实际上是descendant
的后代)。原因是在
HeightDiff()
的while循环中,在一些迭代之后,descendant
将取值D:
。因此,equivalent()
将返回true并停止循环,使descendant
成为空字符串之前多了一步。我之前不知道
D:
指的是当前目录,因此才会问这个问题。有没有办法修改
HeightDiff
函数以获得正确的输出?用
while(descendant != parent)
替换equivalent()
条件是否可以在所有情况下给出正确的输出?如果不能,那么有其他解决方案吗?
GetCurrentDirectory
win32函数来检查当前目录的设置位置。 - durkmurder