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

 给朋友写的时候,顺便贴上来了
开发环境为 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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值