[英]Extracting the immediate parent directory from a file path using boost
假設我有
String t = "c:/foo/foo1/foo2/foo3/file.txt"
我想提取"foo3/file.txt"
。
我該怎么做(使用boost或std)?
到目前為止,這是我一直在嘗試的方法:
boost::filesystem::path pathToObject(t);
我可以使用pathToObject.filename()
提取文件名。 我玩過t.find_last_of("/")
但是我真的很需要t.find_second_to_last_of("/")
。
string::find_last_of
有一個可選參數 ,可讓您指定要查找的字符串的距離。
所以你可以定義
size_t second_to_last = t.find_last_of("/", t.find_last_of("/")-1);
std::string file_with_parent = t.substr(second_to_last+1);
第二個參數告訴他只能在最后一個/
之前進行搜索。
警告:如果您有類似"C:/bli/bla//blubb.txt"
類的東西,這可能與您想要的不同。 通常,路徑可能很復雜且令人困惑,嘗試用字符串操作來克服它們僅適用於行為良好的輸入,而這通常是無法假定的。
因此,我建議使用適當的工具來完成這項工作。*但是,由於該問題聲稱find_last_of
不能完成這項工作,因此我很想提醒人們,標准設施並不像許多人認為的那樣完全無能為力。
*我懷疑boost path lib是一個,但是我從未使用過。
提取這樣的路徑是很奇怪的。 也許您正在尋找相對路徑? boost文件系統為此提供了一個工具。 請務必仔細閱讀文檔 。 但是要回答你的問題:
namespace bfs= boost::filesystem;
int main( ) {
bfs::path path( "c:/foo/foo1/foo2/foo3/file.txt" );
bfs::path target( path );
target.remove_filename( );
target= target.filename( ) / path.filename( );
std::cout << target << std::endl;
}
我沒有方便的編譯器來測試它,但是基於此處的示例,此代碼基本上應該可以工作或為您指明正確的方向。 即使按照我在這里寫的內容,也可能會稍微簡化一下。
path p1( "c:/foo/foo1/foo2/foo3/file.txt" );
path p2;
for (path::iterator it(p1.end()), int i = 0; it != p1.begin() && i < 2; --it, ++i) {
path temp = p2;
p2 = it;
p2 /= temp;
}
這是我最終使用的解決方案:
std::string t = pathObject.parent_path().filename().string();
t.append("/");
t.append(pathObject.filename().string());
使用parent_path
給了我路徑。 然后,我使用filename
僅提取目錄。 然后,我附加了子目錄的filename
。
以下方法返回直接父目錄。
#include <string>
string getParentDirectory(string& filePath)
{
if (filePath.empty() == false)
{
size_t toPos = filePath.find_last_of('\\') - 1;
if (toPos != string::npos)
{
size_t fromPos = filePath.find_last_of('\\', toPos);
if (fromPos != string::npos)
{
return filePath.substr(fromPos + 1, toPos - fromPos);
}
}
}
return "";
}
int main()
{
string str = "D:\\Devs\\Test\\sprite.png";
string parentDir = getParentDirectory(str);
return 0;
}
它打印出parentDir的值為“ Test”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.