動作確認
C++ Builder XE4
RAD Studio 10.2 Tokyo Update 2 (追記: 2018/01/09)
やりたいこと
C:\Users\user\Documents\RAD Studio\Projects\00-work
の最下層フォルダ00-workを以下のようにprefix文字(L"PRE_"など)をつけたい。
C:\Users\user\Documents\RAD Studio\Projects\PRE_00-work
code v0.1
Unit1.cpp
//---------------------------------------------------------------------------
# include <vcl.h>
# pragma hdrstop
# include <IOUtils.hpp>
# include <memory>
# include "Unit1.h"
//---------------------------------------------------------------------------
# pragma package(smart_init)
# pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
}
//---------------------------------------------------------------------------
String getDeepestDir(String srcstr)
{
// [AAA\\BBB\\CCC\\DDD]から[DDD]を取得する
std::unique_ptr<TStringList> list(new TStringList);
list->StrictDelimiter = true;
list->Delimiter = L'\\';
list->DelimitedText = ExcludeTrailingPathDelimiter(srcstr);
return list->Strings[list->Count - 1];
}
String addPrefixToDeepestDirName(String srcstr, String prefix)
{
String dpst = getDeepestDir(srcstr);
String prnt = TDirectory::GetParent(srcstr);
return prnt + L"\\" + prefix + dpst;
}
void __fastcall TForm1::Button1Click(TObject *Sender)
{
String path = L"C:\\Users\\user\\Documents\\RAD Studio\\Projects\\00-work";
String res = addPrefixToDeepestDirName(path, L"PRE_");
OutputDebugString(res.c_str());
}
//---------------------------------------------------------------------------
結果
デバッグ出力: C:\Users\user\Documents\RAD Studio\Projects\PRE_00-work プロセス Project1.exe (3176)
関連
c++ builder / fileIO > 最下層フォルダ名を取得する実装
code v0.2
addPrefixToDeepestDirName()を以下のように修正した。
文字列の最後にL"\\"
がついている時に置換が失敗して、最下層フォルダのさらに下にフォルダを作ってしまう不具合に気づいたため。
String addPrefixToDeepestDirName(String srcstr, String prefix)
{
String wrksrc = ExcludeTrailingPathDelimiter(srcstr);
String dpst = getDeepestDir(wrksrc);
String prnt = TDirectory::GetParent(wrksrc);
return prnt + L"\\" + prefix + dpst;
}