LoginSignup
3
2

More than 5 years have passed since last update.

VisualC++(MFC)で複数の引数から絶対パスを返す関数

Last updated at Posted at 2017-05-16

MFCで、可変長引数を用いて絶対パスを取得する関数。
C++11以上で動作。Visual Studio 2013で動作確認。

C++Builder版
http://qiita.com/mm_sys/items/7633cb1b52788a533176

2017/06/01 マルチバイトとUNICODE両方使えるようにLPTSTRに変更。(今までTCHARのことをよくわかってなかった・・・)

C++11
#include <vector>
#include "atlpath.h"

#include <iostream>
// (省略)

template<typename ... Args>
CString JoinPath(const Args ... strs) {
    std::vector<CString>tmp_vector_str = { strs ... };
    CString tmp_path;
    if (PathIsRelative(tmp_vector_str[0])) {
        LPTSTR fileName;
        GetFullPathName(tmp_vector_str[0], MAX_PATH, tmp_path.GetBuffer(MAX_PATH), &fileName);
    }
    else {
        tmp_path = tmp_vector_str[0];
    }
    for (int i = 1; i < tmp_vector_str.size(); i++) {
        CPath path;
        path.Combine(tmp_path, tmp_vector_str[i]);
        tmp_path = static_cast<CString>(path);
    }
    return tmp_path;
}

// 使用例
printf("%S\n", JoinPath(L"1"));
// C:\(省略)\1
printf("%S\n", JoinPath(L"1", L"2", L"3"));
// C:\(省略)\1\2\3
printf("%S\n", JoinPath(L"C:\\",L"1", L"2", L"3"));
// C:\1\2\3

3
2
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2