わびさびサンプルソース

WindowsやHTML5などのプログラムのサンプルコードやフリーソフトを提供します。

相対パスへ変換する

PathRelativePathTo()関数は、ベースとなるパスと、相対パスを取得したいパスを 指定すると、相対パスを返します。PathRelativePathTo()関数を利用するには、 "Shlwapi.lib"をリンクする必要があります。

#include <stdio.h>
#include <tchar.h>
#include <iostream>
#include <string>
#include <windows.h>
#include <shlwapi.h>



#pragma comment( lib, "Shlwapi.lib" )



/*
	相対パスへ変換する
*/
std::wstring GetRelativePath
(
	  std::wstring oFolder
	, std::wstring oPath
)
{
	wchar_t waBuf[ MAX_PATH * 2 ];

	// 相対パスを取得する
	if ( FALSE != ::PathRelativePathTo(
			  waBuf
			, oFolder.c_str()			// ベースとなるフォルダ
			, FILE_ATTRIBUTE_DIRECTORY
			, oPath.c_str()				// 相対パスを取得したパス
			, FILE_ATTRIBUTE_ARCHIVE
			) ) {

		// 変換結果を返す
		return( waBuf );
	}

	// 変換失敗
	return( L"" );
}



int _tmain
(
	  int argc
	, _TCHAR* argv[]
)
{
	// 相対パスへ変換する
	std::wstring oRelativePath = GetRelativePath(
			  L"c:¥¥OrgApps¥¥Fav¥¥WabisabiSampleSource"
			, L"c:¥¥OrgApps¥¥Fav¥¥WabisabiSampleSource¥¥Tools¥¥test"
		);

	// 結果を表示
	std::wcout << oRelativePath << std::endl;
}



実行結果

.\Tools\test






わびさびサンプルソース

WindowsやHTML5などのプログラムのサンプルコードやフリーソフトを提供します。