假设我有
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("/")
。
答案 0 :(得分:2)
<body>
<div class="featuredtitle">
<div class="visable">
<ul>
<li><h1>nameone</h1></li>
<li><h1>nametwo</h1></li>
<LI><h1>namethree</h1></li>
</ul>
</div>
</div>
<div id="fullpage">
<div class="section active" id="section0"></div>
<div class="section" id="section1"></div>
<div class="section" id="section2"></div>
<div class="section" id="section3"></div>
</div>
</body>
有一个optional argument,可让您指定所查看字符串的距离。
所以你可以定义
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"
不能完成这项工作,我觉得很有必要提醒人们标准设施并非完全无能为力正如许多人似乎相信它们一样。
*我怀疑增强路径lib是一个,但我从未使用它。
答案 1 :(得分:1)
提取这样的路径是相当奇怪的。也许你正在寻找相对路径? boost filesystem有一个工具。请务必仔细查看documentation。但要回答你的问题:
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;
}
答案 2 :(得分:0)
我没有编译器方便测试它,但根据这里的例子,这段代码基本上应该工作或指向正确的方向。它甚至可以从我在这里写的内容中简化一点。
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;
}
答案 3 :(得分:0)
以下是我最终使用的解决方案:
std::string t = pathObject.parent_path().filename().string();
t.append("/");
t.append(pathObject.filename().string());
使用parent_path
给了我一条路径。然后我使用filename
来提取目录。然后我附加了子目录的filename
。
答案 4 :(得分:0)
以下方法返回直接父目录。
const prevLoading = usePrevious(isLoading);
useEffect(() => {
if (!prevLoading && isLoading) {
getOrders({
page: page + 1,
query: localQuery,
held: localHoldMode,
statuses: filterMap[filterBy],
})
.then((o) => {
const { orders: fetchedOrders } = o.data;
const allOrders = orders.concat(fetchedOrders);
setOrders(allOrders);
setPage(page + 1);
setPagesSeen([...pagesSeen, page + 1]);
setPrefetchedOrders(null);
setIsLoading(false);
})
.catch(e => console.error(e.message));
}
}, [isLoading, preFetchedOrders, orders, page, pagesSeen]);
const getNextPage = () => {
// This will scroll back to the top, and also trigger the prefetch for the next page on the way up.
goToTop();
if (pagesSeen.includes(page + 1)) {
return setPage(page + 1);
}
if (prefetchedOrders) {
const allOrders = orders.concat(prefetchedOrders);
setOrders(allOrders);
setPage(page + 1);
setPagesSeen([...pagesSeen, page + 1]);
setPrefetchedOrders(null);
return;
}
setIsLoading(true);
};
它打印出parentDir的值为“ Test”。