开发者

C++ get directory prefix

开发者 https://www.devze.com 2023-03-12 21:03 出处:网络
For example I have the string \"root/data/home/file1.txt\"I would like to get \"root/data/home\" Is th开发者_如何学Pythonere a convenient function in C++ that allows me to do this or should I code it

For example I have the string "root/data/home/file1.txt" I would like to get "root/data/home" Is th开发者_如何学Pythonere a convenient function in C++ that allows me to do this or should I code it myself?


You can do basic string manipulation, i.e.

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:

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).


There's certainly no convenient function in the language itself. The string library provides find_last_of, which should do well.


This is rather platform-dependent. For example, Windows uses '\' for a path separator (mostly), Unix uses '/', and MacOS (prior to OSX) uses ':'.

The Windows-specific API is PathRemoveFileSpec.

0

精彩评论

暂无评论...
验证码 换一张
取 消