简体   繁体   English

C++ 获取目录前缀

[英]C++ get directory prefix

For example I have the string "root/data/home/file1.txt" I would like to get "root/data/home" Is there a convenient function in C++ that allows me to do this or should I code it myself?例如,我有字符串"root/data/home/file1.txt"我想获得"root/data/home" C++ 中是否有方便的 function 允许我这样做,还是我应该自己编写代码?

You can do basic string manipulation, ie您可以进行基本的字符串操作,即

std::string path = "root/data/home/file1.txt";
// no error checking here
std::string prefix = path.substr(0, path.find_last_of('/'));

or take a third option like Boost.Filesystem :或采取第三种选择,如Boost.Filesystem

namespace fs = boost::filesystem;
fs::path path = "root/data/home/file1.txt";
fs::path prefix = path.parent_path();

If you're on a POSIX system, try dirname(3) .如果您使用的是 POSIX 系统,请尝试dirname(3)

There's certainly no convenient function in the language itself.语言本身肯定没有方便的 function 。 The string library provides find_last_of , which should do well.字符串库提供了find_last_of ,它应该做得很好。

This is rather platform-dependent.这是相当依赖于平台的。 For example, Windows uses '\' for a path separator (mostly), Unix uses '/' , and MacOS (prior to OSX) uses ':' .例如,Windows 使用'\'作为路径分隔符(大部分),Unix 使用'/' ,MacOS(在 OSX 之前)使用':'

The Windows-specific API is PathRemoveFileSpec .特定于 Windows 的 API 是PathRemoveFileSpec

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM