您的位置:首页 > 其它

在同一个根目录下,给出一个〖参照路径〗,计算〖当前程序目录〗与〖参照路径〗的相对路径

2008-12-01 00:55 351 查看
给朋友写的时候,顺便贴上来了
开发环境为 vc8 + boost1.36

比如给定参照路径为 "c://temp1//temp2",
程序所在目录为 "c://Documents and Settings//Administrator//桌面//boost练习//pathProcess",
则 〖当前程序目录〗与〖参照路径〗的相对路径: ../../../../temp1/temp2

#include <iostream>
#include <string>
#include <boost/filesystem/operations.hpp>

using namespace std;
using namespace boost;
namespace fs = boost::filesystem;

void main()
{
//假设 c://temp1//temp2 为参照目录
const std::string strConsultPath = "c://temp1//temp2";
fs::path ConsultPath( strConsultPath );

if ( !fs::exists( ConsultPath ) )
{
std::cout << "目录 " << strConsultPath << " 不存在" << std::endl;
std::system("pause");
return ;
}

if ( !fs::is_directory( strConsultPath ) )
{
std::cout << strConsultPath << " 不是目录" << std::endl;
std::system("pause");
return ;
}

std::cout << " 参照目录: " << std::endl;
std::cout << strConsultPath << std::endl;
std::cout << std::endl;

//当前程序的完整路径
std::string strCurPath = boost::filesystem::current_path().directory_string();

//当前程序相对于 根目录 的路径
std::string strRet;
while ( 1 )
{
//当前程序的上一级目录
int nPos = strCurPath.rfind('//');
if ( -1 != nPos )
{
strCurPath = strCurPath.substr( 0, nPos );
// 根目录是 C 盘,所以这里固定写成 "c:"
// 实际开发中,要注意一下,最好注意大小写的区分
if ( strCurPath != "c:" )
{
strRet += "..//";
}
else
{
break;
}
}
}

std::cout << " 当前程序相对于 根目录 的路径: " << std::endl;
std::cout << strRet << std::endl;
std::cout << std::endl;

std::cout << " 当前程序相对于 参照目录 的路径: " << std::endl;
int nTmpPos = strConsultPath.find( "//" );
std::string strTmpPath = strConsultPath.substr( nTmpPos + 1, strConsultPath.length() );
strRet += strTmpPath;
std::cout << strRet << std::endl; // ../../../../temp1/temp2

std::cout << std::endl;
std::cout << std::endl;
std::cout << std::endl;

std::system("pause");
return;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐